LeetCode – Remove Linked List Elements (Java)

Remove all elements from a linked list of integers that have value val.

Example

Given: 1 --> 2 --> 6 --> 3 --> 4 --> 5 --> 6, val = 6
Return: 1 --> 2 --> 3 --> 4 --> 5

Java Solution

The key to solve this problem is using a helper node to track the head of the list.

public ListNode removeElements(ListNode head, int val) {
    ListNode helper = new ListNode(0);
    helper.next = head;
    ListNode p = helper;
 
    while(p.next != null){
        if(p.next.val == val){
            ListNode next = p.next;
            p.next = next.next; 
        }else{
            p = p.next;
        }
    }
 
    return helper.next;
}
Category >> Algorithms >> Interview  
If you want someone to read your code, please put the code inside <pre><code> and </code></pre> tags. For example:
<pre><code> 
String foo = "bar";
</code></pre>
  • Saurabh

    Throws null pointer at if (pointer.next.val == val) pointer.next = pointer.next.next; for a LL of size 1

  • someone

    void del_node (node_t **l, int value) {
    node_t *prev = NULL;
    node_t *cur = *l;

    while (cur) {
    if (cur->data == value) {
    node_t *t = cur;
    if (prev) { /* Not list head */
    prev->next = cur->next;
    } else { /* List head */
    *l = cur->next;
    }
    cur = cur->next;
    free(t);
    } else {
    prev = cur;
    cur = cur->next;
    }
    }
    }

  • Rakesh Venkatesh

    No need to deference as it will be garbage collected

  • cabbar

    leak*

  • cabbar

    Do you dereference deleted node? Because if you don’t isn’t it memory lead?

  • Vimukthi Weerasiri

    Without a helper node. Comments are welcome 🙂

    public ListNode removeElements(ListNode head, int val) {
    if (head == null) return null;
    ListNode pointer = head;
    while (pointer.next != null) {
    if (pointer.next.val == val) pointer.next = pointer.next.next;
    else pointer = pointer.next;
    }
    return head.val == val ? head.next : head;
    }