Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Delete duplicates in linked list O(1) space
package com.interviewbytes.linkedlists;
public class DeleteDuplicates {
public ListNode deleteDuplicates(ListNode head) {
ListNode sentinel = new ListNode(0);
ListNode current = sentinel;
while (head != null) {
boolean duplicateDetected = false;
while (head.next != null && head.val == head.next.val) {
duplicateDetected = true;
head = head.next;
}
if (!duplicateDetected) {
current.next = head;
current = current.next;
}
head = head.next;
}
current.next = null;
return sentinel.next;
}
}
package com.interviewbytes.linkedlists;
public class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
}
}
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.