-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.interviewbytes.linkedlists; | |
public class ListNode { | |
int val; | |
ListNode next; | |
ListNode(int x) { | |
val = x; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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