题目
代码
代码1:双指针:
class Solution:
def deleteDuplicates(self, head: ListNode) -> ListNode:
if not head:
return head
dummy = prev = head
node = head.next
while node:
#print(prev.val,node.val)
if node.val == prev.val:
node = node.next
else:
prev.next = node
prev = prev.next
node = node.next
prev.next = None
return dummy
代码2:单指针
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def deleteDuplicates(self, head: ListNode) -> ListNode:
cur = head
while cur:
while cur.next and cur.next.val == cur.val:
cur.next = cur.next.next # skip duplicated node
cur = cur.next # not duplicate of current node, move to next node
return head