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>

  1. Vimukthi Weerasiri on 2015-7-19

    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;
    }

  2. cabbar on 2015-8-5

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

  3. cabbar on 2015-8-5

    leak*

  4. Rakesh Venkatesh on 2015-10-16

    No need to deference as it will be garbage collected

  5. someone on 2015-12-10

    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;
    }
    }
    }

  6. Saurabh on 2016-5-29

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

  7. Anshul on 2017-7-29

    ListNode removeKFromList(ListNode l, int k) {

    if(null == l) {
    return null;
    }

    ListNode pointer = l;

    while (pointer.next != null) {
    if (pointer.next.value == k) pointer.next = pointer.next.next;
    else pointer = pointer.next;
    }

    return l.value == k ? l.next : l;

    }

Leave a comment

*