forked from sarthakd999/Hacktoberfest2021-2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
linkedlist.cpp
198 lines (119 loc) · 2.33 KB
/
linkedlist.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
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
#include <iostream>
using namespace std;
// blueprint of Node
class Node{
public:
int data;
Node* next;
Node(int d){
data = d;
next = NULL;
}
};
// blueprint of linked list
class LinkedList{
public:
Node* head;
// default constructor
LinkedList(){
head = NULL;
}
// constructor
LinkedList(Node* n){
head = n;
}
void insertAtEnd(Node* n){
Node* ptr = head;
while(ptr->next!=NULL){
ptr = ptr->next;
}
ptr->next = n;
cout << "inserted at the end"<<endl;
}
// insert at begngging
void insertAtBeg(Node* n){
n->next = head;
head = n;
}
// delete 1st node in LL
void deleteFirst(){
Node* temp = head;
head = head->next;
delete temp;
}
// delete from last
void deleteLast(){
Node* ptr = head;
while(ptr->next->next!=NULL){
ptr = ptr->next;
}
Node* temp = ptr->next;
ptr->next = NULL;
delete temp;
}
// insert at given position
void insterAt(int position,Node* n){
Node* ptr = head;
int i = 1;
while(i<position-1){
ptr = ptr->next;
i++;
}
n->next = ptr->next;
ptr->next = n;
}
// search in a linked list
void search(int val){
Node* ptr = head;
while(ptr!=NULL){
if(ptr->data==val){
cout << "found: "<<ptr->data<<endl;
return;
}
ptr = ptr->next;
}
cout << "not found"<<endl;
}
// sorted insert in a liked list
void sortedInsert(Node* n){
}
// print the linked list
void printList(){
if(head==NULL){
cout << "empty List"<<endl;
}
else{
Node* ptr = head;
while(ptr!=NULL){
cout << ptr->data<<"->";
ptr = ptr->next;
}
cout << endl;
}
}
};
int main(){
Node* node1 = new Node(1);
Node* node2 = new Node(2);
Node* node3 = new Node(3);
Node* node4 = new Node(4);
Node* node5 = new Node(5);
Node* node6 = new Node(6);
Node* node7 = new Node(7);
Node* node8 = new Node(8);
Node* node9 = new Node(9);
LinkedList* myList = new LinkedList(node1); // initilised the head node
myList->insertAtEnd(node2);
myList->insertAtEnd(node3);
myList->insertAtEnd(node4);
myList->insertAtEnd(node5);
myList->insertAtEnd(node6);
myList->insertAtEnd(node7);
myList->insertAtEnd(node8);
// myList->insertAtBeg(node9);
myList->deleteFirst();
myList->deleteLast();
myList->insterAt(3,node9);
myList->printList();
myList->search(10 );
}