-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRemove Duplicates from Sorted List.cpp
40 lines (38 loc) · 1.22 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
//Remove Duplicates from Sorted List
class Solution {
public:
ListNode *deleteDuplicates(ListNode *head) {
if(head == NULL) return head;
ListNode *node = head;
while(node -> next){ // we need to compare with the next val, so here we should consider about the next node not node!!
int v = node -> val;
if(node -> next -> val == v){
node -> next = node -> next -> next;
}else{
node = node -> next;
}
}
return head;
}
};
//Remove Duplicates from Sorted List ii
class Solution {
public:
ListNode *deleteDuplicates(ListNode *head) {
if(head == NULL || head -> next == NULL) return head;
ListNode *dummy = new ListNode(-1);
dummy -> next = head;
ListNode *node = dummy;
while(node -> next && node -> next -> next){
if(node -> next -> next -> val == node -> next -> val){
int v = node -> next -> val;
while(node -> next && node -> next -> val == v){
node -> next = node -> next -> next;
}
}else{
node = node -> next;
}
}
return dummy -> next;
}
};