Skip to content

Instantly share code, notes, and snippets.

@InterviewBytes
Created June 8, 2017 23:44
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/247c758ee508a9d6bfa871c7fcc9dc5b to your computer and use it in GitHub Desktop.
Save InterviewBytes/247c758ee508a9d6bfa871c7fcc9dc5b to your computer and use it in GitHub Desktop.
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