Skip to content

Latest commit

 

History

History
35 lines (25 loc) · 894 Bytes

File metadata and controls

35 lines (25 loc) · 894 Bytes

Level: Easy

Topic: Linked List Recursion

Question

Given the head of a linked list and an integer val, remove all the nodes of the linked list that has 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]

Intuition

Code

Time: O(n)
Space: O(1)

public ListNode removeElements(ListNode head, int val) {
    ListNode dummy = new ListNode(0, head);
    ListNode prev = dummy;

    while (head != null) {
        if (head.val == val)
            prev.next = head.next;
        else
            prev = head;
        head = head.next;
    }
    return dummy.next;
}