Remove Duplicates from Sorted List
Difficulty: Easy · Pattern: Linked List · LeetCode #83
Given the head of a sorted linked list, delete duplicates so each value appears once. Return the head.
Examples
text
1 → 1 → 2 → 1 → 2
1 → 1 → 2 → 3 → 3 → 1 → 2 → 3Hints
- Duplicates are adjacent. Compare each node with its next.
Approach
Walk with cur; while cur.next has the same value, bypass it (cur.next = cur.next.next); otherwise advance cur. O(n), O(1).
Complexity
Time: O(n). Space: O(1).
Python solution
def deleteDuplicates(head):
cur = head
while cur and cur.next:
if cur.next.val == cur.val:
cur.next = cur.next.next
else:
cur = cur.next
return headJavaScript solution
function deleteDuplicates(head) {
let cur = head;
while (cur && cur.next) { if (cur.next.val === cur.val) cur.next = cur.next.next; else cur = cur.next; }
return head;
}