# 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>
```
• N G Sundarasekaran

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

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

}

• Alik Elzin

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

• Hemant Kumar Kushwaha

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

• thanks for this post this is informative
java training in velachery

• West

don’t be so dork add additional check on begining

• Anshul

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;

}

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