-
-
Notifications
You must be signed in to change notification settings - Fork 48
Expand file tree
/
Copy path0203-remove-linked-list-elements.py
More file actions
46 lines (38 loc) · 1.09 KB
/
0203-remove-linked-list-elements.py
File metadata and controls
46 lines (38 loc) · 1.09 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
# 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 removeElements(self, head: Optional[ListNode], val: int) -> Optional[ListNode]:
dummy = ListNode(0, head)
prev = dummy
curr = head
while curr:
if curr.val == val:
prev.next = curr.next
curr = curr.next
else:
prev = curr
curr = curr.next
return dummy.next
head = ListNode()
val = 7
print(Solution().removeElements(head, val))
head = ListNode(1)
head.next = ListNode(2)
head.next.next = ListNode(6)
head.next.next.next = ListNode(3)
head.next.next.next.next = ListNode(4)
head.next.next.next.next.next = ListNode(5)
head.next.next.next.next.next.next = ListNode(6)
val = 6
print(Solution().removeElements(head, val))
head = ListNode(7)
head.next = ListNode(7)
head.next.next = ListNode(7)
head.next.next.next = ListNode(7)
val = 7
print(Solution().removeElements(head, val))