Problem
Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.
Example 1:
1 |
|
Example 2:
1 |
|
Explanation
-
We need to check if the current element is same as its previous element and its next element, so we need to create a dummy node, and a pre pointer initially points at the dummy node, a current pointer initially points at the first element, and we compare current pointer element with pre pointer element and current.next element.
-
If the current element is not the same as its previous and next element, then we need to store it into a linkedlist, so we can store the first distinct element into
dummy.next
, at the end we can returndummy.next
. -
After we store the matching current element, we need to move
pre
andcur
pointers to point at the next element. Because nowcur
points at the correct next element and we want to cut off the result list and input list, we can setpre.next
tonull
, one example is input list is[1, 2, 2]
, we want the result list to be[1]
. Also, initially, thedummy.next
isnull
and it’s not pointing to the head of the input linkedlist.
Solution
1 |
|