-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path083.RemoveDuplicatesfromSortedList.cpp
More file actions
43 lines (39 loc) · 1.01 KB
/
083.RemoveDuplicatesfromSortedList.cpp
File metadata and controls
43 lines (39 loc) · 1.01 KB
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
/*Question:
Given a sorted linked list, delete all duplicates such that each element appear only once.
For example,
Given 1->1->2, return 1->2.
Given 1->1->2->3->3, return 1->2->3.
*/
//Code:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* deleteDuplicates(ListNode* head) {
if (head == nullptr || head->next == nullptr){
return head;
}
auto preNode = head;
auto curNode = head->next;
ListNode* nextNode = nullptr;
while (curNode != nullptr){
if (curNode->val != preNode->val) {
preNode = curNode;
curNode = curNode->next;
}
else{
nextNode = curNode->next;
preNode->next = nextNode;
delete(curNode);
curNode = nextNode;
}
}
return head;
}
};