-
Notifications
You must be signed in to change notification settings - Fork 19
/
Copy pathlist-remove-duplicates.cpp
60 lines (52 loc) · 1.19 KB
/
list-remove-duplicates.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
// http://www.geeksforgeeks.org/remove-duplicates-from-a-sorted-linked-list/
#include <iostream>
using namespace std;
class Node {
public:
int data;
Node *next;
Node(int data) {
this->data = data;
this->next = NULL;
}
};
void printList(Node *head);
void removeDuplicates(Node *head) {
if (head == NULL || head->next == NULL)
return;
Node *prev, *curr;
prev = head;
curr = head->next;
while (curr != NULL) {
if (prev->data == curr->data) {
prev->next = curr->next;
curr = prev->next;
continue;
}
prev = prev->next;
curr = curr->next;
}
}
void printList(Node *head) {
if (head == NULL)
return;
while (head != NULL) {
cout<<head->data<<" ";
head = head->next;
}
}
int main()
{
Node *head = new Node(1);
head->next = new Node(3);
head->next->next = new Node(3);
head->next->next->next = new Node(3);
head->next->next->next->next = new Node(4);
cout<<"original: ";
printList(head);
removeDuplicates(head);
cout<<endl<<"after duplicate removal: ";
printList(head);
cout<<endl;
return 0;
}