LeetCode — Remove Duplicates from Sorted List II

Example of question
Example of question
public ListNode deleteDuplicates(ListNode head) {
//base case - empty list or single node (there can be no duplicates)
if(head==null || head.next==null)
return head;

//storing head in another node so that original list is not lost
ListNode temp = head;
//for storing previous node at each point
ListNode prev = null;

//since we will be comparing value of adjacent nodes we should ensure that both are not null
while(temp!=null && temp.next!=null){
//if duplicate found
if(temp.val==temp.next.val){
//move forward until non duplicate element found
while(temp!=null && temp.next!=null && temp.val==temp.next.val)
temp = temp.next;

//if previous is not null means we are not at head
//so previous should point to next node after chain of duplicates
if(prev!=null)
prev.next = temp.next;

//else head needs to point to first non duplicate
else
head = temp.next;
}
//else make previous equal to current node to move ahead with traversal
else
prev = temp;

//increment current node for next set of nodes
temp = temp.next;
}

//return head node of updated list
return head;
}

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store