-
Notifications
You must be signed in to change notification settings - Fork 4
/
Solution.cpp
55 lines (48 loc) · 1.3 KB
/
Solution.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
50
51
52
53
54
#include <string>
#include <vector>
#include <iostream>
#include <sstream>
#include <algorithm>
#include <tuple>
#include <deque>
using namespace std;
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution {
public:
// this is a non recursive version
ListNode* deleteDuplicates(ListNode* head) {
if (head == NULL or head->next == NULL) return head;
auto ptr = head;
while (ptr != NULL and ptr->next != NULL) {
if (ptr->next->val == ptr->val) {
auto p = ptr->next;
while (p != NULL and p->val == ptr->val) {
p = p->next;
}
ptr->next = p;
}
ptr = ptr->next;
}
return head;
}
// this is a recursive version
ListNode* deleteDuplicates(ListNode* head) {
if (head == NULL or head->next == NULL) return head;
if (head->next->val != head->val) {
head->next = this->deleteDuplicates(head->next);
return head;
}
auto p = head->next;
while (p != NULL and p->val == head->val) p = p -> next;
head->next = p == NULL ? p : this->deleteDuplicates(p);
return head;
}
};
int main() {
Solution s;
return 0;
}