Remove Duplicates from Sorted List — Single Pass
Advertisement
Problem 211 · Remove Duplicates from Sorted List
Difficulty: Easy · Pattern: Pointer Walk
Solutions
// C++
ListNode* deleteDuplicates(ListNode* head) {
ListNode* cur = head;
while (cur && cur->next) {
if (cur->val == cur->next->val) cur->next = cur->next->next;
else cur = cur->next;
}
return head;
}
// Java
public ListNode deleteDuplicates(ListNode head) {
ListNode cur = head;
while (cur != null && cur.next != null) {
if (cur.val == cur.next.val) cur.next = cur.next.next;
else cur = cur.next;
}
return head;
}
# Python
def deleteDuplicates(head):
cur = head
while cur and cur.next:
if cur.val == cur.next.val: cur.next = cur.next.next
else: cur = cur.next
return head
Complexity
- Time: O(n)
- Space: O(1)
Advertisement