Remove Duplicates from Sorted List
Given a sorted linked list, delete all duplicates such that each element appear only once.
Analysis:
straightforward question, if it's a sorted array we don't need hashtable but keep comparing next node with current node to remove duplicates.
Solution:
ListNode *deleteDuplicates(ListNode *head) {
ListNode *dummy = new ListNode(0);
dummy->next = head; // use dummy head to avoid taking care of first node later
ListNode *current = head; // use single pointer to traverse the list
while(current) // two while loops, it still takes O(n) cuz every node once is visited once
{
while(current->next) // In this loop comparing adjacent nodes to remove duplicates
{
if(current->next->val == current->val) // Removing next node cuz it's a duplicate
{
ListNode *temp = current->next;
current->next = current->next->next;
delete temp;
continue;
}
else
{
break; // Or the next node is NOT a duplicate, break and move forward
}
}
current = current->next;
}
return dummy->next; // return next element of dummy header which is beginning of new list
}
No comments:
Post a Comment