forked from KnowledgeCenterYoutube/LeetCode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
203_Remove_Linked_list_Elements
67 lines (60 loc) · 1.65 KB
/
203_Remove_Linked_list_Elements
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
61
62
63
64
65
66
Leetcode 203: Remove Linked List Elements
Detailed video explanation: https://youtu.be/YIng7Pf6oa4
==============================================
C++:
====
Iterative:
----------
ListNode* removeElements(ListNode* head, int val) {
if(!head) return head;
ListNode *prev = nullptr, *curr = head;
while(curr){
if(curr->val == val){
if(!prev)
head = curr->next;
else
prev->next = curr->next;
}else
prev = curr;
curr = curr->next;
}
return head;
}
Recursive:
---------
ListNode* removeElements(ListNode* head, int val) {
if(!head) return head;
ListNode * h = removeElements(head->next, val);
if(head->val == val) return h;
head->next = h;
return head;
}
Java:
====
public ListNode removeElements(ListNode head, int val) {
if(head == null) return head;
ListNode prev = null, curr = head;
while(curr != null){
if(curr.val == val){
if(prev == null)
head = curr.next;
else
prev.next = curr.next;
}else
prev = curr;
curr = curr.next;
}
return head;
}
Python3:
=======
def removeElements(self, head: ListNode, val: int) -> ListNode:
if head == None: return head
prev, curr = None, head
while curr != None:
if curr.val == val:
if prev == None: head = curr.next
else: prev.next = curr.next
else:prev = curr
curr = curr.next
return head