Remove Duplicates from Sorted List II
Problem
Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.
Example
Given 1->2->3->3->4->4->5, return 1->2->5.
Given 1->1->1->2->3, return 2->3.
Solutions
If we use a pointer p, bascially we are comparing p.next and p.next.next
- if they are different, no duplicates, simply move
pforward; - if they are the same, we should skip all nodes with
p.next.valand letp.nextpoint to the next value. Note thatpdoes NOT move in this case, onlyp.nextis updated.
Since the head node may be removed, we should use a dummy node to help remember the head position.