Leetcode题解之 —— 移除链表元素

思路


方法一: 转化为数组

  • 通过filtermap高阶API解决

方法二: 修改next指针

  • 创建firstNode节点, 指向head
  • 两个指针lastNodecurrentNode
    • 前者指向firstNode, 表示上一个节点
    • 后者指向head, 当前遍历的节点

题解


数组解法:

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
const cache = [];
let current = head;

while (current) {
cache.push(new ListNode(current.val));
current = current.next;
}

if (!cache.length) {
return null;
}

const temp = cache
.filter((v) => v.val !== val)
.map((v, i, self) => {
v.next = self[i + 1];

return v;
})

if (!temp.length) {
return null;
}

return temp[0];

指针解法:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
/**
* @param {ListNode} head
* @param {number} val
* @return {ListNode}
*/
var removeElements = function (head, val) {
const firstNode = new ListNode(0);
firstNode.next = head;

let [lastNode, currentNode] = [firstNode, head];

while (currentNode) {
if (currentNode.val === val) {
lastNode.next = currentNode.next;
} else {
lastNode = currentNode;
}
currentNode = currentNode.next;
}

return firstNode.next || null;
};