Given a sorted linked list, delete all duplicates such that each element appear only once.
For example,
Given 1->1->2, return 1->2.
Given 1->1->2->3->3, return 1->2->3.
For example,
Given 1->1->2, return 1->2.
Given 1->1->2->3->3, return 1->2->3.
public ListNode deleteDuplicates(ListNode head) {
if (head == null || head.next == null) // No node or only a single node
return head;
ListNode previous = head, current = head.next;
// Remove the current node if its value is the same with its previous node
while (current != null) {
if (current.val == previous.val) { // Duplicates found
previous.next = current.next;
current = current.next;
} else { // Move to the next node
previous = current;
current = current.next;
}
}
return head;
}
Read full article from LeetCode - Remove Duplicates from Sorted List | Darren's Blog