-
Notifications
You must be signed in to change notification settings - Fork 0
/
remove-linked-list-elements.js
59 lines (49 loc) · 1.13 KB
/
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
/**
* Definition for singly-linked list.
* function ListNode(val, next) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
*/
/**
* 移除链表元素
* @param {ListNode} head
* @param {number} val
* @return {ListNode}
*/
var removeElements = function (head, val) {
// 1. 迭代-方式一 (更好理解) (dummy node)
let dummyNode = new ListNode(0, head);
let curr = dummyNode;
while (curr.next) {
if (val === curr.next.val) {
curr.next = curr.next.next;
continue;
}
curr = curr.next;
}
return dummyNode.next;
// 2. 迭代-方式二 (dummy node)
// let curr = head;
// let dummyNode = new ListNode(-1);
// dummyNode.next = head;
// let prev = dummyNode;
// while (curr) {
// if (curr.val === val) {
// prev.next = curr.next;
// } else {
// prev = curr;
// }
// curr = curr.next;
// }
// return dummyNode.next;
// 3. 递归
// let curr = head;
// if (curr) {
// curr.next = removeElements(curr.next, val);
// if (curr.val === val) {
// return curr.next;
// }
// }
// return curr;
};