Skip to content

Instantly share code, notes, and snippets.

@InterviewBytes
Created June 9, 2017 05:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save InterviewBytes/d4d00d3380dc1acc88871b7a8a3abe76 to your computer and use it in GitHub Desktop.
Save InterviewBytes/d4d00d3380dc1acc88871b7a8a3abe76 to your computer and use it in GitHub Desktop.
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