-
Notifications
You must be signed in to change notification settings - Fork 0
/
203-Remove_Linked_List_Elements.py
44 lines (33 loc) · 1.08 KB
/
203-Remove_Linked_List_Elements.py
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
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution1:
def removeElements(self, head: ListNode, val: int) -> ListNode:
while head:
if head.val == val:
head = head.next
else:
break
if not head:
return head
head_node = head
while head_node.next != None:
if head_node.next.val == val:
head_node.next = head_node.next.next
else:
head_node = head_node.next
return head
class Solution2:
def removeElements(self, head: ListNode, val: int) -> ListNode:
HEAD = ListNode(0)
HEAD.next = head
pre, cur = HEAD, head
while head:
if head.val == val:
pre.next = head.next
else:
pre = head
head = head.next
return HEAD.next