-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path203-RemoveElements.py
More file actions
60 lines (49 loc) · 1.49 KB
/
203-RemoveElements.py
File metadata and controls
60 lines (49 loc) · 1.49 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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
# Python3
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
# 迭代
class Solution:
def removeElements(self, head: ListNode, val: int) -> ListNode:
if not head:
return None
dummy = ListNode(0, head)
pre = dummy
while head:
if head.val == val:
tmp = head.next
pre.next = head.next
head = tmp
continue
head = head.next
pre = pre.next
return dummy.next
class Solution:
def removeElements(self, head: ListNode, val: int) -> ListNode:
if not head:
return None
dummy = ListNode(0, head)
pre = dummy
while pre.next:
if pre.next.val == val:
pre.next = pre.next.next
else:
pre = pre.next
return dummy.next
# 递归
class Solution:
def removeElements(self, head: ListNode, val: int) -> ListNode:
if not head:
return None
if head.val == val:
head = self.removeElements(head.next, val)
else:
head.next = self.removeElements(head.next, val)
return head
class Solution:
def removeElements(self, head: ListNode, val: int) -> ListNode:
if not head:
return None
head.next = self.removeElements(head.next, val)
return head.next if head.val == val else head