82. Remove Duplicates from Sorted List II
Last updated
Was this helpful?
Last updated
Was this helpful?
Given the head
of a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list. Return the linked list sorted as well.
Example 1:
Example 2:
Constraints:
The number of nodes in the list is in the range [0, 300]
.
-100 <= Node.val <= 100
The list is guaranteed to be sorted in ascending order.
Linked List
A dummy head is created and connects to head
. Assign 3 pointers onto the linked list: pre
(which starts from the dummy head), cur
(which starts from head
) and next
(which is only initialized when used). Traverse the linked list with cur
. The loop condition is cur != nil && cur.Next != nil
. There are 2 scenarios in the loop. If cur
's next value is NOT equal to that of cur
, it means that the node cur
pointing to needs to be preserved. Thus, just move forward and assign pre
to the cur
's old position. Otherwise, we find a string of duplicated nodes and cur
is pointing to the head of it. We use next
to find the next node whose value is not same as cur
's. When we find, we assign pre.Next
to next
, and move cur
to pre
because cur will move one step forward after every single loop. At last, we return the next node of dummy head.
Time complexity:
Space complexity: