203. Remove Linked List Elements
203. Remove Linked List Elements
题目
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:
![](https://assets.leetcode.com/uploads/2021/03/06/removelinked-list.jpg)
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, 104]
. 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. 移除元素](./0027.md)
- [237. 删除链表中的节点](./0237.md)
- [2095. 删除链表的中间节点](https://leetcode.com/problems/delete-the-middle-node-of-a-linked-list)