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

12 thoughts on “LeetCode – Remove Linked List Elements (Java)”

  1. public static ListNode removeNodes(ListNode listHead, int x) {
    ListNode head = listHead;
    while(head != null && head.data == x) {
    head = head.next;
    }

    if(head != null) {
    ListNode node = head;
    ListNode nextNode = node.next;
    while(nextNode != null) {
    if(nextNode.data > x) {
    node.next = nextNode.next;
    } else {
    node = nextNode;
    }
    nextNode = node.next;
    }
    }

    return head;

    }


  2. A solution without helper below. It has more edge cases like updating root.


    Node remove(Node root, int val)
    {
    Node prev = null;

    for (Node n = root; n != null ; n = n.next)
    {
    if (n.val != val)
    {
    if (prev == null)
    {
    root == n;
    }
    prev = n;
    continue;
    }

    if (prev != null)
    {
    prev.next = n.next;
    }
    }

    if (prev == null) return null;

    return root;
    }

  3. How to pass the ListNode head parameter while calling this function in main method.

  4. 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;

    }

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

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

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

Leave a Comment