-
Notifications
You must be signed in to change notification settings - Fork 0
/
tut37.cpp
160 lines (142 loc) · 3.04 KB
/
tut37.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
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
#include <iostream>
#include <map>
using namespace std;
class Node{
public:
int data;
Node* next;
Node(int data){
this -> data = data;
this -> next = NULL;
}
~Node(){
if(this->next != NULL){
delete next;
this->next = NULL;
}
}
};
void printLL(Node* &head, Node* &tail){
if(head == NULL){
cout<<"List is empty"<<endl;
return;
}
Node* temp = head;
while(temp != NULL){
cout<<temp->data<<" ";
temp = temp->next;
}
cout<<endl;
cout<<"Head = "<<head->data<<endl;
cout<<"Tail = "<<tail->data<<endl;
cout<<endl;
}
void insertAtHead(Node* &head, int d){
Node* temp = new Node(d);
temp->next = head;
head = temp;
}
void insertAtTail(Node* &tail, int d){
Node* temp = new Node(d);
tail->next = temp;
tail = tail->next;
}
void insertAtPos(Node* &head, Node* &tail, int p, int d){
if(p==1){
insertAtHead(head, d);
return;
}
else{
Node* temp = new Node(d);
Node* pre = head;
int cnt = 1;
while(cnt<p-1){
pre = pre->next;
cnt++;
}
temp->next = pre->next;
pre->next = temp;
if(temp->next == NULL){
tail = temp;
}
}
}
void deleteN(Node* &head, Node* &tail, int p){
if(p==1){
Node* temp = head;
head = head->next;
temp->next = NULL;
delete temp;
}
else{
Node* pre = NULL;
Node* cur = head;
int cnt = 1;
while(cnt<p){
pre = cur;
cur = cur->next;
cnt++;
}
pre->next = cur->next;
cur->next = NULL;
delete cur;
//For updating tail
if(pre->next == NULL){
tail = pre;
}
}
}
int getLen(Node* &head){
Node* temp = head;
int count = 0;
while(temp!=NULL){
count++;
temp = temp->next;
}
return count;
}
bool unique(Node* head, int n){
Node* pre = head;
int count = 1;
while(count<n-1){
Node* cur = pre->next;
while(cur!=NULL){
if(pre->data==cur->data){
return false;
}
cur=cur->next;
}
pre = pre->next;
count++;
}
return true;
}
int main(){
Node* node1 = new Node(2);
Node* head = node1;
Node* tail = node1;
deleteN(head, tail, 1);
printLL(head, tail);
insertAtHead(head, 1);
printLL(head, tail);
insertAtHead(head, 0);
printLL(head, tail);
insertAtTail(tail, 4);
printLL(head, tail);
insertAtTail(tail, 10);
printLL(head, tail);
insertAtPos(head, tail, 3, 15);
printLL(head, tail);
deleteN(head, tail, 5);
printLL(head, tail);
// insertAtPos(head, tail, 1, 15);
// printLL(head, tail);
int n = getLen(head);
if(unique(head, n)){
cout<<"Given Linked List is unique"<<endl;
}
else{
cout<<"Given Linked List is not unique"<<endl;
}
return 0;
}