Remove Duplicates from Sorted List

Posted by Bill on March 11, 2023

Remove Duplicates from Sorted List

Given the head of a sorted linked list, delete all duplicates such that each element appears only once. Return the linked list sorted as well.

Example 1: Input: head = [1,1,2] Output: [1,2]

Example 2: Input: head = [1,1,2,3,3] Output: [1,2,3]

C++ Solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
ListNode* deleteDuplicates(ListNode* head) {
  ListNode *ret = head;
  ListNode *last = nullptr;
  ListNode *cur = head;
  set<int> mySet;
  while (cur != nullptr) {
    if (mySet.count(cur->val) == 0) {
      mySet.insert(cur->val);
      last = cur;
      cur = cur->next;
    } else {
      cur = cur->next;
      last->next = cur;
    }
  }
  return ret;
}