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
.
Check for the coding detail below
/*
Key to solve: two points
1. curr point =head & next point =head.next
2. two cases:
2.1 duplication was found, skip it
2.2 move both curr and next nodes forward
*/
public static ListNode deleteDuplicates(ListNode head) {
//check for corner case
if(head==null || head.next==null) return head;
ListNode curr=head;
ListNode nextNode=curr.next;
while(nextNode!=null){
//duplication was found
if(curr.val==nextNode.val){
//skip duplicated node
curr.next=nextNode.next;
//move nextNode to next Node
nextNode=nextNode.next;
}else {
//move both curr and nextNode forward
curr = curr.next;
nextNode = nextNode.next;
}
}
return head;
}