- Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path0083-remove-duplicates-from-sorted-list.cpp
35 lines (32 loc) · 1.02 KB
/
0083-remove-duplicates-from-sorted-list.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
/*
83. Remove Duplicates from Sorted List
Submitted: November 26, 2024
Runtime: 0 ms (beats 100.00%)
Memory: 16.08 MB (beats 99.94%)
*/
/**
* 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) {}
* };
*/
classSolution {
public:
ListNode* deleteDuplicates(ListNode* head) {
if (head == nullptr) returnnullptr; // empty list
if (head->next == nullptr) return head; // list with one item cannot have duplicates
ListNode* p=head;
while (p != nullptr && p->next != nullptr) {
// while loop to account for multiple duplicates
while (p->next != nullptr && p->next->val == p->val) { // p->next and p have same value
p->next=p->next->next; // remove the node which p->next formerly referred to
}
p = p->next;
}
return head;
}
};