简繁EN

LeetCodeNo. 113

[LeetCode with Python] 82. Remove Duplicates from Sorted List II

Contents

Problem

Problem page: https://leetcode.com/problems/remove-duplicates-from-sorted-list-ii/
Topics: Linked List
Difficulty: Medium

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

For example,
Given 1->2->3->3->4->4->5, return 1->2->5.
Given 1->1->1->2->3, return 2->3.


Analysis

This one's a lot like Remove Duplicates from Sorted List, except that instead of keeping one copy of each repeated value, you delete all its copies.


Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution:
# @param head, a ListNode
# @return a ListNode
def deleteDuplicates(self, head):
if None == head or None == head.next:
return head

new_head = ListNode(-1)
new_head.next = head
parent = new_head
cur = head
while None != cur and None != cur.next: ### check cur.next None
if cur.val == cur.next.val:
val = cur.val
while None != cur and val == cur.val: ### check cur None
cur = cur.next
parent.next = cur
else:
cur = cur.next
parent = parent.next

return new_head.next

Article link: https://xnerv.wang/en/leetcode-remove-duplicates-from-sorted-list-ii/