-
Notifications
You must be signed in to change notification settings - Fork 154
/
remove-linked-list-elements.js
62 lines (53 loc) · 1013 Bytes
/
remove-linked-list-elements.js
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
/**
* Remove Linked List Elements
*
* Remove all elements from a linked list of integers that have value val.
*
* Example:
*
* Input: 1->2->6->3->4->5->6, val = 6
* Output: 1->2->3->4->5
*/
/**
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/
/**
* Recursion
*
* @param {ListNode} head
* @param {number} val
* @return {ListNode}
*/
const removeElementsR = (head, val) => {
if (!head) {
return null;
}
head.next = removeElementsR(head.next, val);
return head.val === val ? head.next : head;
};
/**
* Non-Recursion
*
* @param {ListNode} head
* @param {number} val
* @return {ListNode}
*/
const removeElements = (head, val) => {
const dummy = new ListNode(0);
let p = dummy;
let node = head;
while (node) {
if (node.val !== val) {
p.next = node;
p = p.next;
}
node = node.next;
}
p.next = null;
return dummy.next;
};
export { removeElements, removeElementsR };