Given the head of a sorted linked list, delete all duplicates so each value appears once. Return the sorted list.
DSA Animator › DSA Revision › Linked List › Remove Duplicates from Sorted List
Remember: in a sorted list, duplicates are neighbours. Skip the next node instead of moving when values match. The video solves Remove Duplicates from Sorted List (LeetCode 83, Easy) with the Linked List Traversal pattern from the Linked List topic, and you can replay every step in the interactive Remove Duplicates from Sorted List animation.
Given the head of a sorted linked list, delete all duplicates so each value appears once. Return the sorted list.
For 1, 1, 2, 3, 3, the result is 1, 2, 3.
Copying values into a set and building a new list uses extra space. The list is sorted, so duplicates sit next to each other.
Walk with one pointer, current. If the next node has the same value, skip it by linking current to the node after it. Otherwise, move current forward.
Current is at the first 1, and the next node is also 1, so skip it. Now the next node is 2, which is different, so move to 2. 2 and 3 differ, so move to 3. The next 3 is a duplicate, so skip it. The list is 1, 2, 3.
In code, loop while current and its next exist. If the values match, set current dot next to current dot next dot next. Otherwise move current, so it's O of n time and O of 1 space.
Remember: in a sorted list, duplicates are neighbours. Skip the next node instead of moving when values match.