Remove Duplicates from Sorted List II


Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.


Given 1->2->3->3->4->4->5, return 1->2->5.

Given 1->1->1->2->3, return 2->3.


If we use a pointer p, bascially we are comparing p.next and p.next.next

  • if they are different, no duplicates, simply move p forward;
  • if they are the same, we should skip all nodes with p.next.val and let p.next point to the next value. Note that p does NOT move in this case, only p.next is updated.

Since the head node may be removed, we should use a dummy node to help remember the head position.

Online Judge