---
# System prepended metadata

title: LC 82. Remove Duplicates from Sorted List II
tags: [medium, leedcode, Linked List, c++]

---

# LC 82. Remove Duplicates from Sorted List II

### [Problem link](https://leetcode.com/problems/remove-duplicates-from-sorted-list-ii/)

###### tags: `leedcode` `medium` `c++` `Linked List`

Given the <code>head</code> of a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list. Return the linked list  **sorted**  as well.

**Example 1:** 
<img alt="" src="https://assets.leetcode.com/uploads/2021/01/04/linkedlist1.jpg" style="width: 500px; height: 142px;" />
```
Input: head = [1,2,3,3,4,4,5]
Output: [1,2,5]
```

**Example 2:** 
<img alt="" src="https://assets.leetcode.com/uploads/2021/01/04/linkedlist2.jpg" style="width: 500px; height: 205px;" />
```
Input: head = [1,1,1,2,3]
Output: [2,3]
```

 **Constraints:** 

- The number of nodes in the list is in the range <code>[0, 300]</code>.
- <code>-100 <= Node.val <= 100</code>
- The list is guaranteed to be  **sorted**  in ascending order.

## Solution 1
#### C++
```cpp=
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* deleteDuplicates(ListNode* head) {
        ListNode *dummy = new ListNode(-1, head);
        ListNode *cur = dummy;
        while (cur->next && cur->next->next) {
            int val = cur->next->val;
            if (val == cur->next->next->val) {
                while (cur->next && cur->next->val == val) {
                    cur->next = cur->next->next;
                }
            } else {
                cur = cur->next;
            }
        }
        return dummy->next;
    }
};
```

>### Complexity
>|             | Time Complexity | Space Complexity |
>| ----------- | --------------- | ---------------- |
>| Solution 1  | O(n)            | O(1)             |

## Note
x
