Remove Linked List Elements (LeetCode 203): Solution and Explanation
Given the head of a singly linked list and a value val, remove every node whose value equals val and return the head of the resulting list. The head itself may need removing, possibly several times in a row.
Watch it run step by step
Try your own input and write the code →Intuition
Removing a node from a singly linked list means changing the next pointer of the node before it so that it skips over the node you want gone. That immediately tells you the traversal must keep track of the previous node, because once you are standing on a node you cannot reach backward.
The awkward part is the head. If the first node matches, there is no previous node to rewire, so a naive solution ends up with a special loop at the start that keeps advancing head while it matches, followed by the general loop for the rest. That works but duplicates logic and is easy to get wrong when the list is something like 7, 7, 7, 7.
A dummy node removes the special case entirely. Create a placeholder node whose next is the real head, and start prev at the dummy. Now every real node, including the first, has a predecessor. Walk curr through the list. When curr matches, splice it out with prev.next = curr.next and leave prev where it is, since the next node could also match. When it does not match, move prev forward to curr. At the end, dummy.next is the new head, which correctly handles the case where every node was removed.
Approach: Dummy head with previous and current pointers
- Create
dummy = ListNode(0, head)so that the real head has a predecessor. - Set
prev = dummyandcurr = head. - While
curris not None, check whethercurr.val == val. - If it matches, set
prev.next = curr.nextto unlinkcurr, and keepprevin place. - If it does not match, advance
prevtocurr. - In both cases advance
curr = curr.next, and when the loop ends returndummy.next.
Step-by-step example
head = [6, 1, 6, 6, 2], val = 6
- The dummy points at the first 6.
previs the dummy andcurris that 6. It matches, sodummy.nextnow points at 1, andprevstays on the dummy. currmoves to 1, which does not match, soprevadvances to the 1 node.currmoves to the second 6, which matches, so1.nextis set to the third 6.prevstays on 1.currmoves to the third 6, which also matches, so1.nextis set to 2.currmoves to 2, which does not match, soprevadvances to 2.currbecomes None and the loop ends.- The function returns
dummy.next, giving the list [1, 2].
Code: Python, Java, C++
1class Solution:
2 def removeElements(self, head: Optional[ListNode], val: int) -> Optional[ListNode]:
3 dummy = ListNode(0, head)
4 prev, curr = dummy, head
5 while curr:
6 if curr.val == val:
7 prev.next = curr.next
8 else:
9 prev = curr
10 curr = curr.next
11 return dummy.next1class Solution {
2 public ListNode removeElements(ListNode head, int val) {
3 ListNode dummy = new ListNode(0);
4 dummy.next = head;
5 ListNode prev = dummy;
6 ListNode curr = head;
7 while (curr != null) {
8 if (curr.val == val) {
9 prev.next = curr.next;
10 } else {
11 prev = curr;
12 }
13 curr = curr.next;
14 }
15 return dummy.next;
16 }
17}1class Solution {
2public:
3 ListNode* removeElements(ListNode* head, int val) {
4 ListNode dummy(0);
5 dummy.next = head;
6 ListNode* prev = &dummy;
7 ListNode* curr = head;
8 while (curr) {
9 if (curr->val == val) {
10 prev->next = curr->next;
11 } else {
12 prev = curr;
13 }
14 curr = curr->next;
15 }
16 return dummy.next;
17 }
18};Time and space complexity
O(n)
Every node is visited exactly once, and each visit does a constant amount of pointer work.
O(1)
Only the dummy node and two pointers are allocated, no matter how long the list is.
Other approaches
Recursion (time O(n), space O(n))
Recursively clean the rest of the list with head.next = removeElements(head.next, val), then return head.next if the head matches or head otherwise. It is very compact, but each node adds a stack frame, so a list of 10,000 nodes can hit recursion limits in some languages.
Advance the head first, then loop (time O(n), space O(1))
Skip leading matches by moving head forward while head.val == val, then run the same predecessor loop starting from the new head. It avoids allocating a dummy node but needs two loops and careful null checks.
Common mistakes
- Advancing
prevafter removing a node. If the next node also matches,prevwould then point at a removed node and the second removal would not stick. - Returning
headinstead ofdummy.next. When the original head is removed,headstill points at the deleted node. - Forgetting the all-match case, such as [7, 7, 7] with
val = 7. The answer must be an empty list, which the dummy approach returns naturally. - In languages with manual memory management, unlinking a node without freeing it, which leaks memory in C++ if the nodes were heap allocated by you.
Frequently asked questions
Why use a dummy node in linked list problems?
A dummy node gives the real head a predecessor, so inserting or deleting at the front uses the same code as anywhere else. It removes special cases and makes the final head simply dummy.next.
Is the recursive solution O(1) space?
No. Each recursive call stays on the call stack until the end of the list is reached, so space is O(n). The iterative dummy-node solution is the constant-space version.
Why does prev not move when a node is removed?
After removing curr, the node now following prev has not been checked yet. Keeping prev in place ensures that if that node also matches, it can be unlinked from the same predecessor.