Skip to content

Instantly share code, notes, and snippets.

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

Embed
What would you like to do?
Remove duplicates from a linked list.
package com.interviewbytes.linkedlists;
public class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
}
}
package com.interviewbytes.linkedlists;
public class RemoveDuplicates {
public ListNode deleteDuplicates(ListNode head) {
if (head == null) return null;
ListNode current = head;
ListNode sentinel = new ListNode(0);
sentinel.next = current;
head = head.next;
while (head != null) {
if (head.val != current.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.