Skip to content

83. Remove Duplicates from Sorted List 👍

  • Time: $O(n)$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
class Solution {
 public:
  ListNode* deleteDuplicates(ListNode* head) {
    ListNode* curr = head;

    while (curr != nullptr) {
      while (curr->next && curr->val == curr->next->val)
        curr->next = curr->next->next;
      curr = curr->next;
    }

    return head;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
class Solution {
  public ListNode deleteDuplicates(ListNode head) {
    ListNode curr = head;

    while (curr != null) {
      while (curr.next != null && curr.val == curr.next.val)
        curr.next = curr.next.next;
      curr = curr.next;
    }

    return head;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
class Solution:
  def deleteDuplicates(self, head: ListNode) -> ListNode:
    curr = head

    while curr:
      while curr.next and curr.val == curr.next.val:
        curr.next = curr.next.next
      curr = curr.next

    return head