乐趣区

82. Remove Duplicates from Sorted List II

Given a sorted linked list, delete all nodes that have duplicatenumbers, leaving only distinct numbers from the original list.
https://leetcode.com/problems…
# 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:
# Two nodes: one to keep head, one to keep tail.
ahead = phead = ListNode(‘null’)

# Two pointers: one to move ahead, one to monitor duplicates.
p = None
c = head

# When move to end, terminate.
while c:
# At the beginning, simple move one step forward.
if p == None:
p = c
# If p and c have different values, need to determine why.
elif p.val != c.val:
# If p and c are neighbors, p must be unique value.
if p.next == c:
phead.next = p
phead = phead.next
phead.next = None
# p gets one step forward.
p = c
# If p and c are not neighbors, ignore nodes with p.val.
else:
p = c
# c moves one step anyway.
c = c.next

# If p is not None (input not empty) and has next, collect last element.
if p != None and p.next == None:
phead.next = p

return ahead.next

退出移动版