Remove Linked List Elements
Easy
Topics
Given the head of a linked list and an integer k, remove all nodes whose value equals k and return the new head. (LeetCode calls this parameter val.)
Example 1
Input: head = [1,2,6,3,4,5,6], k = 6 Output: [1,2,3,4,5]
Example 2
Input: head = [7,7,7,7], k = 7 Output: []
Constraints
- 0 <= number of nodes <= 10^4
- 0 <= Node.val, k <= 50
Editorial — intuition, approach, complexity and pitfalls
Intuition
Deleting a node from a singly linked list means changing its predecessor's pointer. That makes the head awkward: it has no predecessor, so removing it needs separate handling — and if several leading nodes all match, that handling has to loop.
A dummy head removes the special case entirely. Allocate one node in front of the real head; now every removable node has a predecessor, the loop is uniform, and the answer is dummy.next — which correctly reflects a new head if the original was deleted.
As with removing duplicates, do not advance after unlinking: the next node may also match.
Approach
- Create
dummypointing athead; setcurrent = dummy. - While
current.nextexists: if its value matches the target, splice it out; else advance. - Return
dummy.next.
Dry Run
remove 6 from 6 -> 1 -> 2 -> 6 -> 3 -> 4 -> 5 -> 6
dummy -> 6 -> 1 -> ...
cur=dummy, next=6 match -> unlink dummy -> 1 -> 2 -> 6 -> ...
cur=dummy, next=1 keep -> advance
cur=1, next=2 keep -> advance
cur=2, next=6 match -> unlink ... 2 -> 3 -> ...
cur=2, next=3 keep -> advance
... 3, 4, 5 kept ...
cur=5, next=6 match -> unlink ... 5 -> null
cur=5, next=null -> stop
answer 1 -> 2 -> 3 -> 4 -> 5 (both leading and trailing 6s gone)Complexity
- Time — O(n): one pass.
- Space — O(1): the dummy node and one pointer.
Common Pitfalls
- Not using a dummy and then handling the head with a single
if. Consecutive matching head nodes need a loop, and this is the most common failure. - Advancing after an unlink, which skips consecutive matches in the middle.
- Returning
headinstead ofdummy.next. If the original head was removed,headpoints at a detached node. - Looping on
currentrather thancurrent.next, which dereferences null at the end.
Full Solution — all languages
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def removeElements(self, head, k):
dummy = ListNode(0, head)
cur = dummy
while cur.next:
if cur.next.val == k:
cur.next = cur.next.next
else:
cur = cur.next
return dummy.nextimport java.util.*;
class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
}
}
class Solution {
public ListNode removeElements(ListNode head, int k) {
ListNode dummy = new ListNode(0);
dummy.next = head;
ListNode cur = dummy;
while (cur.next != null) {
if (cur.next.val == k) cur.next = cur.next.next;
else cur = cur.next;
}
return dummy.next;
}
}#include <bits/stdc++.h>
using namespace std;
struct ListNode {
int val;
ListNode *next;
ListNode(int x): val(x), next(nullptr) {
}
};
class Solution {
public: ListNode* removeElements(ListNode* head, int k) {
ListNode dummy(0);
dummy.next = head;
ListNode* cur = &dummy;
while (cur->next) {
if (cur->next->val == k) cur->next = cur->next->next;
else cur = cur->next;
}
return dummy.next;
}
};/** Node shape: { val, next }. Build/return plain objects or use this ctor. */ function ListNode(val, next) {
this.val = (val === undefined ? 0 : val);
this.next = (next === undefined ? null : next);
}
/**
* @param {ListNode} head
* @param {number} k
* @return {ListNode}
*/ var removeElements = function(head, k) {
const dummy = new ListNode(0, head);
let cur = dummy;
while (cur.next) {
if (cur.next.val === k) cur.next = cur.next.next;
else cur = cur.next;
}
return dummy.next;
};