Untitled

 avatar
unknown
plain_text
14 days ago
735 B
3
Indexable
public ListNode removeElements(ListNode head, int val) {
    ListNode dummy = new ListNode(-1); // Create a dummy node
    dummy.next = head; // Point dummy to the head of the list

    ListNode prev = dummy; // Start 'prev' at dummy
    ListNode temp = head;  // Start 'temp' at the head of the list

    while (temp != null) {
        if (temp.val == val) {
            // Skip the current node
            prev.next = temp.next;
            temp.next = null;
        } else {
            // Move 'prev' to the current node if no deletion
            prev = temp;
        }
        // Move 'temp' to the next node
        temp = temp.next;
    }

    return dummy.next; // Return the head of the updated list
}
Leave a Comment