-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path083 Remove Duplicates from Sorted List II.py
More file actions
46 lines (35 loc) · 1.15 KB
/
083 Remove Duplicates from Sorted List II.py
File metadata and controls
46 lines (35 loc) · 1.15 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
"""
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.
Author: Rajeev Ranjan
"""
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def deleteDuplicates(self, head):
"""
Two pointers
:param head: ListNode
:return: ListNode
"""
dummy = ListNode(0)
dummy.next = head
pre = dummy
while pre.next:
cur = pre.next
if cur.next and cur.next.val==cur.val: # duplicated
# find the next non_duplicate
next_non_duplicate = cur.next
while next_non_duplicate and cur.val==next_non_duplicate.val:
next_non_duplicate = next_non_duplicate.next
# remove all duplicated nodes
pre.next = next_non_duplicate
else:
pre = pre.next
return dummy.next