forked from mandliya/algorithms_and_data_structures
-
Notifications
You must be signed in to change notification settings - Fork 0
/
removeDuplicatesFromSortedList.cpp
77 lines (70 loc) · 1.41 KB
/
removeDuplicatesFromSortedList.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
/**
* Given a sorted linkedlist remove duplicates from it.
* 5->5->5->7->7->9->11->13->13->15->15
* 5->7->9->11->13->15
*/
#include <iostream>
struct Node {
int data;
Node * next;
Node( int d ) : data{ d }, next{ nullptr } { }
};
void insert( Node * & head, int data )
{
Node * newNode = new Node(data);
if ( head == nullptr ) {
head = newNode;
} else {
Node * temp = head;
while( temp->next != nullptr ) {
temp = temp->next;
}
temp->next = newNode;
}
}
void printList( Node * head )
{
while( head ) {
std::cout << head->data << "-->";
head = head->next;
}
std::cout << "NULL" << std::endl;
}
void removeDuplicates ( Node * head )
{
if ( !head || (head && !(head->next))) {
return;
}
Node * currNode = head;
Node * nextNode = nullptr;
while( currNode ) {
nextNode = currNode->next;
while(nextNode && nextNode->data == currNode->data) {
nextNode = nextNode->next;
}
currNode->next = nextNode;
currNode = nextNode;
}
}
int main()
{
Node * head = nullptr;
// 5->5->5->7->7->9->11->13->13->13->15->15
insert(head, 5);
insert(head, 5);
insert(head, 5);
insert(head, 7);
insert(head, 7);
insert(head, 9);
insert(head, 11);
insert(head, 13);
insert(head, 13);
insert(head, 13);
insert(head, 13);
insert(head, 15);
insert(head, 15);
printList(head);
removeDuplicates(head);
printList(head);
return 0;
}