[LeetCode] 82. Remove Duplicates from Sorted List II_Medium tag: Linked List

时间:2021-05-05 05:17:39

Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinctnumbers from the original list.

Example 1:

Input: 1->2->3->3->4->4->5
Output: 1->2->5

Example 2:

Input: 1->1->1->2->3
Output: 2->3

这个题目跟[LeetCode] 83. Remove Duplicates from Sorted List_Easy tag: Linked List很类似,但是有可能要把head都去掉,所以还是要加上dummy node,并且使得dummy.next = head, 同时设置pre = dummy instead of None, 另外while loop判断条件为head and head.next, 最后返回dummy.next.

Code

class ListNode:
def __init__(self, x):
self.val = x
self.next = None class Solution:
def removeDup2(self, head):
dummy = ListNode(0)
dummy.next = head
pre = dummy
while (pre.next and pre.next.next):
if pre.next.val == pre.next.next.val:
val = pre.next.val
while (pre.next and pre.next.val == val): # 把重复的点都删掉
pre.next = pre.next.next
else:
pre = pre.next
return dummy.next

2)

class Solution:
def removeDup2(self, head):
dummy = ListNode(0)
dummy.next = head
pre = dummy
while head and head.next:
if head.val == head.next.val:
val = head.val
while head and head.val == val:
pre = head.next
head.next = None
head = pre.next
else:
pre = head
head = head.next
return dummy.next