title | description | keywords | |||||||
---|---|---|---|---|---|---|---|---|---|
203. 移除链表元素 |
LeetCode 203. 移除链表元素题解,Remove Linked List Elements,包含解题思路、复杂度分析以及完整的 JavaScript 代码实现。 |
|
Given the head
of a linked list and an integer val
, remove all the nodes
of the linked list that has Node.val == val
, and return the new head.
Example 1:
Input: head = [1,2,6,3,4,5,6], val = 6
Output: [1,2,3,4,5]
Example 2:
Input: head = [], val = 1
Output: []
Example 3:
Input: head = [7,7,7,7], val = 7
Output: []
Constraints:
- The number of nodes in the list is in the range
[0, 10^4]
. 1 <= Node.val <= 50
0 <= val <= 50
删除链表中所有指定值的结点。
按照题意做即可。
/**
* @param {ListNode} head
* @param {number} val
* @return {ListNode}
*/
var removeElements = function (head, val) {
if (!head) return head;
let res = new ListNode(0, head);
let prev = res;
while (prev.next) {
if (prev.next.val === val) {
prev.next = prev.next.next;
} else {
prev = prev.next;
}
}
return res.next;
};
题号 | 标题 | 题解 | 标签 | 难度 | 力扣 |
---|---|---|---|---|---|
27 | 移除元素 | [✓] | 数组 双指针 |
🟢 | 🀄️ 🔗 |
237 | 删除链表中的节点 | [✓] | 链表 |
🟠 | 🀄️ 🔗 |
2095 | 删除链表的中间节点 | [✓] | 链表 双指针 |
🟠 | 🀄️ 🔗 |
3217 | 从链表中移除在数组中存在的节点 | 数组 哈希表 链表 |
🟠 | 🀄️ 🔗 | |
3263 | 将双链表转换为数组 I 🔒 | 数组 链表 双向链表 |
🟢 | 🀄️ 🔗 | |
3294 | 将双链表转换为数组 II 🔒 | 数组 链表 双向链表 |
🟠 | 🀄️ 🔗 |