Skip to content

Instantly share code, notes, and snippets.

@InterviewBytes InterviewBytes/ListNode.java Secret
Created Jun 9, 2017

Embed
What would you like to do?
Remove all elements from a linked list of integers that have value val.
package com.interviewbytes.linkedlists;
public class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
}
}
package com.interviewbytes.linkedlists;
public class RemoveElements {
public ListNode removeElements(ListNode head, int val) {
ListNode sentinel = new ListNode(0);
ListNode current = sentinel;
while (head != null) {
if (head.val != val) {
current.next = head;
current = current.next;
}
head = head.next;
}
current.next = null;
return sentinel.next;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.