-
Notifications
You must be signed in to change notification settings - Fork 40
/
RemoveLinkedListElements.js
57 lines (52 loc) · 1.42 KB
/
RemoveLinkedListElements.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
// Source : https://leetcode.com/problems/remove-linked-list-elements/
// Author : Dean Shi
// Date : 2015-06-16
/**********************************************************************************
*
* Remove all elements from a linked list of integers that have value val.
*
* Example
* Given: 1 --> 2 --> 6 --> 3 --> 4 --> 5 --> 6, val = 6
* Return: 1 --> 2 --> 3 --> 4 --> 5
*
* Credits:Special thanks to @mithmatt for adding this problem and creating all test cases.
*
**********************************************************************************/
/**
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/
/**
* Recursion
* @param {ListNode} head
* @param {number} val
* @return {ListNode}
*/
var removeElements = function(head, val) {
if (!head) return head;
head.next = removeElements(head.next, val);
return head.val === val ? head.next : head;
};
/**
* Iteration
* @param {ListNode} head
* @param {number} val
* @return {ListNode}
*/
var removeElements = function(head, val) {
let headNode, prevNode, currNode
headNode = prevNode = new ListNode()
prevNode.next = currNode = head
while (currNode) {
if (currNode.val !== val) {
prevNode = prevNode.next
} else {
prevNode.next = currNode.next
}
currNode = currNode.next
}
return headNode.next
};