跳至主要內容

203. 移除链表元素


203. 移除链表元素open in new window

🟢   🔖  递归 链表  🔗 力扣open in new window LeetCodeopen in new window

题目

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移除元素open in new window[✓]数组 双指针
237删除链表中的节点open in new window[✓]链表
2095删除链表的中间节点open in new window链表 双指针
3217从链表中移除在数组中存在的节点open in new window数组 哈希表 链表
3263将双链表转换为数组 I 🔒open in new window数组 链表 双向链表
3294将双链表转换为数组 II 🔒open in new window数组 链表 双向链表