边工作边刷题:70天一遍leetcode: day 23-1
Remove Duplicates from Sorted List II
要点:在内外两层循环,inner loop用来判断当前点是否有重复,outer loop找下一个判断点。在inner loop单用一个指针是不够的,需要用两个指针,一个沿着重复点移动,一个记录初始点,最后比较是否有移动来判断是否有重复。
错误点:
- pre在有重复的情况下要next设为None,否则最后一组重复点还会连着
# 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
"""
dummy = ListNode(0)
dummy.next = head
pre = dummy
cur = head
while cur:
curi = cur
while curi.next and curi.next.val==curi.val:
curi=curi.next
if curi == cur:
pre.next=cur
pre=pre.next
else:
pre.next = None
cur = curi.next
return dummy.next