-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path82-remove-duplicates-from-sorted-list-ii.cpp
49 lines (44 loc) · 1.69 KB
/
82-remove-duplicates-from-sorted-list-ii.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
// Title: Remove Duplicates from Sorted List II
// Description:
// Given the head 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.
// Link: https://leetcode.com/problems/remove-duplicates-from-sorted-list-ii/
// Time complexity: O(n)
// Space complexity: O(1)
/**
* 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 dummyHead(0xDEADBEEF, head);
ListNode *prevNode = &dummyHead;
while (prevNode->next != NULL) {
ListNode *beginNode = prevNode->next, *endNode = beginNode->next;
// extend the range if a duplicate number is found
while (endNode != NULL && endNode->val == beginNode->val) {
endNode = endNode->next;
}
// check if the range contains more than 1 node
if (beginNode->next != endNode) {
// delete the nodes if the range contains more than 1 node
do {
prevNode->next = beginNode->next;
delete beginNode;
beginNode = prevNode->next;
} while (beginNode != endNode);
} else {
// proceed to the next node otherwise
prevNode = prevNode->next;
}
}
return dummyHead.next;
}
};