forked from jaisinha/DSA-practice
-
Notifications
You must be signed in to change notification settings - Fork 0
/
linked list 1.cpp
179 lines (108 loc) · 2.78 KB
/
linked list 1.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
#include<bits/stdc++.h>
using namespace std;
#define ll long long int
#define tc int t; cin >> t; while(t--)
//..............###....****************************.....###..........//
//..............###....*......Kshitij Mishra .....*.....###..........//
//..............###....****************************.....###..........//
#define endl "\n"
#define all(x) x.begin(), x.end()
#define int long long int
void faster() {
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
#ifndef ONLINE_JUDGE
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
#endif
}
class node{
public:
int data;
node* next;
node(int val){
data = val;
next = NULL;
}
};
// insertion at head;
void insertHead(node* &head, int val){
node* temp = new node(val);
temp->next = head;
head = temp;
}
// printing
void print(node* head){
node* temp = head;
while(temp != NULL){
cout << temp->data << " ";
temp = temp-> next;
}
}
// insert at tail
void insertTail(node* &head, int val){
node* d = new node(val);
node* temp = head;
while(temp->next != NULL){ // temp ka next equal nhi hona chahiye null ke agar ho means ye last node hai
temp = temp->next;
}
temp-> next = d;
}
// to search on linked list
bool search(node* &head, int val){
node* temp = head;
while(temp != NULL){
if(temp->data == val){
return true;
}
else{
temp = temp->next;
}
}
return false;
}
void deleteNode(node* &head, int target){
node* temp = head;
// agar pehla element hi delete karna hai
if(temp -> data == target){
head = head->next;
delete temp;
return;
}
// agr linked list hi empty hui
if(head == NULL){
return;
}
// agar sirf 1 element hai aur whi delete karna hai
if(head->next == NULL){
head = head->next;
delete temp;
return;
}
// agr n node ko delte karna hai toh n-1 node ko pakadna hoga
// n-1 node ka address ko n+1 ko point karna hoga
while(temp->next->data != target){
temp = temp->next;
}
node* n = temp->next;
temp->next = temp->next->next;
delete n;
}
signed main(){
faster();
node* a = new node(1);
node* head = a;
insertHead(head, 2);
insertTail(head, 3);
print(head);
deleteNode(head, 2);
cout << "\n";
print(head);
deleteNode(head,1);
cout << endl;
print(head);
deleteNode(head,3);
cout << endl;
print(head);
}