[/dsa/leetcode]

203 - Remove Linked List Elements

Friday, 18 September 2026

<easy> [problem]

Strip the matching prefix first so the head is safe, then unlink matches from behind with a trailing pointer that only advances over survivors.

{linked list}{two pointers}{recursion}

Problem

Given the head of a linked list and an integer val, remove all the nodes of the linked list that have Node.val == val, and return the new head.

Input: head = [1,2,6,3,4,5,6], val = 6
Output: [1,2,3,4,5]

Input: head = [], val = 1
Output: []

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

Approach

Removing a node means pointing the node before it at the node after it, so we need a prev that trails behind. That’s the same pair as 83: prev is the last node kept and curr is scanning ahead. The difference is that here the value being dropped can sit at the front, and the front has nothing before it to rewire.

So deal with the head separately. Walk it forward while it matches, which also covers a list that is entirely matches, since head just ends up nullptr. After that loop the first node is either gone or is a keeper, and the rest of the walk never has to think about the head again.

Then for each curr:

  • matches — unlink it with prev->next = curr->next, leaving prev where it is.
  • doesn’t match — it stays, so prev moves up to it.
head = [1,2,6,3,6], val = 6
strip: 1 != 6, head stays

prev=null curr=1   keep    -> prev=1, curr=2
prev=1    curr=2   keep    -> prev=2, curr=6
prev=2    curr=6   unlink  -> 2->3,   curr=3
prev=2    curr=3   keep    -> prev=3, curr=6
prev=3    curr=6   unlink  -> 3->null, curr=null
[1,2,3]
class Solution {
public:
    ListNode* removeElements(ListNode* head, int val) {
        while (head != nullptr && head->val == val) {
            head = head->next;
        }
        ListNode* curr = head;
        ListNode* prev = nullptr;
        while(curr != nullptr) {
            if(curr->val == val) {
                prev->next = curr->next;
            } else {
                prev = curr;
            }
            curr = curr->next;
        }
        return head;
    }
};

Another version of this with dummy node may look like.

ListNode* removeElements(ListNode* head, int val) {
    ListNode dummy(0, head);
    ListNode* prev = &dummy;
    while (prev->next) {
        if (prev->next->val == val) prev->next = prev->next->next;
        else prev = prev->next;
    }
    return dummy.next;
}
  • time: O(n) - each node is looked at once
  • space: O(1) - two pointers, nodes are relinked in place
quantinium © 2026