KatInterview

203. Remove Linked List Elements

EasySolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The core task is to traverse a singly-linked list and remove all nodes that have a specific value, val. The main challenge lies in correctly managing the pointers to restructure the list. Special cases to consider are removing the head node (or multiple consecutive head nodes), removing nodes from the middle or at the end of the list, and handling an empty list.

Solution

Remove Linked List Elements in Python

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def removeElements(self, head: Optional[ListNode], val: int) -> Optional[ListNode]:
        # Create a dummy node to act as a placeholder for the new head.
        # This simplifies edge cases like removing the original head.
        dummy = ListNode(0, head)
        
        # 'prev' will point to the last node that is not to be removed.
        # 'curr' will iterate through the list.
        prev, curr = dummy, head
        
        while curr:
            if curr.val == val:
                # If the current node's value matches 'val',
                # we bypass it by setting the previous node's next pointer
                # to the current node's next. 'prev' does not advance.
                prev.next = curr.next
            else:
                # If the value doesn't match, we keep the current node
                # by advancing the 'prev' pointer.
                prev = curr
            
            # Move to the next node in the list.
            curr = curr.next
            
        # The modified list starts from the node after the dummy node.
        return dummy.next

Remove Linked List Elements in Java

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode removeElements(ListNode head, int val) {
        // Create a dummy node that points to the head.
        // This simplifies removal, especially for the head node.
        ListNode dummy = new ListNode(0);
        dummy.next = head;
        
        // 'prev' will track the last valid node.
        ListNode prev = dummy;
        // 'curr' will iterate through the list.
        ListNode curr = head;
        
        while (curr != null) {
            if (curr.val == val) {
                // If the current node's value is 'val', skip it by
                // linking the previous node to the current node's next.
                // 'prev' does not advance.
                prev.next = curr.next;
            } else {
                // If the value is not 'val', this node should be kept.
                // Move 'prev' to 'curr'.
                prev = curr;
            }
            // Move 'curr' to the next node.
            curr = curr.next;
        }
        
        // The new head of the list is pointed to by dummy.next.
        return dummy.next;
    }
}

Remove Linked List Elements in C++

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* removeElements(ListNode* head, int val) {
        // Create a dummy node that points to the head of the list.
        // This helps handle cases where the head itself needs to be removed.
        ListNode* dummy = new ListNode(0, head);
        
        // 'prev' will track the last valid node in the resulting list.
        ListNode* prev = dummy;
        // 'curr' will iterate through the original list.
        ListNode* curr = head;
        
        while (curr != nullptr) {
            if (curr->val == val) {
                // If the current node's value matches 'val', we need to remove it.
                // We do this by updating the 'next' pointer of the previous node
                // to skip the current node. 'prev' does not advance.
                prev->next = curr->next;
            } else {
                // If the current node's value does not match 'val', it's a valid node.
                // We update 'prev' to point to this current node.
                prev = curr;
            }
            // Move to the next node in the list.
            curr = curr->next;
        }
        
        // The modified list starts after the dummy node.
        // Storing the new head before deleting the dummy node.
        ListNode* newHead = dummy->next;
        delete dummy;
        return newHead;
    }
};

Remove Linked List Elements in TypeScript

/**
 * Definition for singly-linked list.
 * class ListNode {
 *     val: number
 *     next: ListNode | null
 *     constructor(val?: number, next?: ListNode | null) {
 *         this.val = (val===undefined ? 0 : val)
 *         this.next = (next===undefined ? null : next)
 *     }
 * }
 */

function removeElements(head: ListNode | null, val: number): ListNode | null {
    // Create a dummy node. This simplifies handling the case where
    // the head node itself needs to be removed.
    const dummy = new ListNode(0, head);
    
    // 'prev' tracks the last valid node.
    let prev: ListNode = dummy;
    // 'curr' iterates through the list.
    let curr: ListNode | null = head;
    
    while (curr !== null) {
        if (curr.val === val) {
            // If the current node's value is the target value,
            // we remove it by updating the previous node's 'next' pointer
            // to skip the current node. 'prev' does not advance.
            prev.next = curr.next;
        } else {
            // If the current node is to be kept, we advance 'prev'
            // to the current node.
            prev = curr;
        }
        // Move to the next node.
        curr = curr.next;
    }
    
    // The new head of the list is the node after the dummy node.
    return dummy.next;
};

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.