-
Notifications
You must be signed in to change notification settings - Fork 0
/
Remove-Duplicates-from-Sorted-List.cpp
112 lines (87 loc) · 1.96 KB
/
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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
/*
* Song Qiang <qiang.song@usc.edu> 2013
*
*/
/*
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.
*/
#include <cmath>
#include <cassert>
#include <vector>
#include <numeric>
#include <iostream>
#include <algorithm>
#include <sstream>
#include <limits>
#include <utility>
using namespace std;
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution {
public:
ListNode *deleteDuplicates(ListNode *head) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if (head == NULL) return head;
ListNode* h = head;
ListNode* t = h;
ListNode* p = h->next;
t->next = NULL;
while (p != NULL)
{
if (p->val == t->val)
{
ListNode* q = p;
p = p->next;
delete q;
}
else
{
ListNode* q = p;
p = p->next;
q->next = NULL;
t->next = q;
t = t->next;
}
}
return h;
}
};
class Solution2 {
public:
ListNode *deleteDuplicates(ListNode *head) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if (head == NULL) return NULL;
ListNode* p = head;
while (p->next != NULL)
if (p->next->val != p->val)
p = p->next;
else {
ListNode* t = p->next;
p->next = t->next;
delete t;
}
return head;
}
};
int
main(int argn, char** argv)
{
Solution s;
}