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
preandcurpointers to point at the next element. Because nowcurpoints at the correct next element and we want to cut off the result list and input list, we can setpre.nexttonull, one example is input list is[1, 2, 2], we want the result list to be[1]. Also, initially, thedummy.nextisnulland it’s not pointing to the head of the input linkedlist.
Solution
1 | |