Q:
给定一个排序链表,删除所有重复的元素,使得每个元素只出现一次。
示例 1:
输入: 1->1->2
输出: 1->2
示例 2:
输入: 1->1->2->3->3
输出: 1->2->3
链接:https://leetcode-cn.com/problems/remove-duplicates-from-sorted-list/description/
思路:做的不是很好
代码:
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def deleteDuplicates(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if not head:
return []
pre = head
stack=[head]
while pre.next:
if pre.next.val == stack[-1].val:
pre = pre.next
else:
stack.append(pre.next)
pre = pre.next
head_ = p = stack.pop(0)
p.next = None
while stack:
tmp = stack.pop(0)
tmp.next = None
p.next = tmp
p = p.next
return head_