- Notifications
You must be signed in to change notification settings - Fork 33
Expand file tree
/
Copy pathlinked_list.cpp
More file actions
Latest commit
136 lines (115 loc) · 2.34 KB
/
Copy pathlinked_list.cpp
File metadata and controls
136 lines (115 loc) · 2.34 KB
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
#include<iostream>
usingnamespacestd;
classnode{
public:
int data;
node*next;
node(int d){
data = d;
next = NULL;
}
~node(){
int temp = data;
if(next!=NULL){
delete next;
next = NULL;
}
cout<<"Deleting node with data "<<temp<<endl;
}
};
voidinsertAtHead(node * &head,int d){
node *n = newnode(d);
n->next = head;
head = n;
}
voidtakeInput(node *&head){
int d;
cin>>d;
while(d!=-1){
insertAtHead(head,d);
cin>>d;
}
}
voidprint(node*head){
while(head!=NULL){
cout<<head->data<<"-->";
head = head->next;
}
cout<<"NULL"<<endl;
}
intlength(node *temp){
int l=0;
while(temp!=NULL){
l++; temp = temp->next;
}
return l;
}
voidinsertInMiddle(node*&head,int d,int p){
if(p==0){
insertAtHead(head,d);
return;
}
int jump=1;
node*temp = head;
while(jump<=p-1){
jump++;
temp = temp->next;
}
node*n = newnode(d);
n->next = temp->next;
temp->next = n;
}
istream& operator>>(istream&is, node*&head){
takeInput(head);
return is;
}
ostream& operator<<(ostream&os, node*head){
print(head);
return os;
}
voiddeleteNode(node*&head,int d){
node* prev = NULL;
node* current = head;
while(current!=NULL){
if(current->data == d){
if(prev==NULL){
///Head Node
node*temp = head;
head = temp->next;
temp->next = NULL;
delete temp;
current = head;
}
else{
///Some Middle Node
node*temp = current;
prev->next = current->next;
//temp->next = NULL;
temp->next = NULL;
delete temp;
}
}
prev = current;
current = current->next;
}
}
intmain(){
node*head=NULL;
cin>>head;
cout<<head;
cout<<"Enter data and postion ";
int d,p;
cin>>d>>p;
insertInMiddle(head,d,p);
cout<<head;
cout<<"Enter the node to delete ";
cin>>d;
deleteNode(head,d);
cout<<head;
/*
delete head;
head = NULL;
cout<<head;
*/
return0;
}