-
-
Notifications
You must be signed in to change notification settings - Fork 48
Expand file tree
/
Copy path0082-remove-duplicates-from-sorted-list-ii.py
More file actions
43 lines (35 loc) · 1.08 KB
/
0082-remove-duplicates-from-sorted-list-ii.py
File metadata and controls
43 lines (35 loc) · 1.08 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
# time complexity: O(n)
# space complexity: O(1)
from typing import Optional
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def deleteDuplicates(self, head: Optional[ListNode]) -> Optional[ListNode]:
dummy = ListNode(-1)
dummy.next = head
curr, prev = head, dummy
while curr:
while curr.next and curr.val == curr.next.val:
curr = curr.next
if prev.next == curr:
prev = prev.next
curr = curr.next
else:
prev.next = curr.next
curr = prev.next
return dummy.next
def traverse(node: Optional[ListNode]):
if node is None:
return
print(node.val)
traverse(node.next)
head = ListNode(1)
head.next = ListNode(2)
head.next.next = ListNode(3)
head.next.next.next = ListNode(3)
head.next.next.next.next = ListNode(4)
head.next.next.next.next.next = ListNode(4)
head.next.next.next.next.next.next = ListNode(5)
traverse(Solution().deleteDuplicates(head))