-
Notifications
You must be signed in to change notification settings - Fork 82
/
Linked List.cpp
127 lines (108 loc) · 2.22 KB
/
Linked List.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
//----------------Linked List-----------------//
//-----Traversal--Insertion--Deletion---------//
#include<bits/stdc++.h>
using namespace std;
class node{
public:
int data;
node* next;
node(){
data=0;
next=NULL;
}
node(int tmp){
data=tmp;
next=NULL;
}
};
class linkedlist {
node* head;
public:
linkedlist(){
head=NULL;
}
void insert_node(int data);
void display ();
void delete_node(int key);
};
void linkedlist::insert_node(int data){
node* new_node= new node(data);
if(head==NULL){
head=new_node;
return;
}
node* temp=head;
while(temp->next!=NULL){
temp=temp->next;
}
temp->next=new_node;
}
//to delete specified node
void linkedlist::delete_node(int key){
node *temp=head, *prev=NULL;
if(temp!=NULL && temp->data==key){
head=temp->next;
delete temp;
return;
}
while(temp!=NULL && temp->data!=key){
prev=temp;
temp=temp->next;
}
if(temp==NULL){
cout<<"ERROR: key not found\n";
delete temp;
return;
}
prev->next=temp->next;
delete temp;
return;
}
void linkedlist::display (){
node* temp=head;
if(head==NULL){
cout<<"list is empty\n";
return;
}
while(temp!=NULL){
cout<<temp->data<<" ";
temp=temp->next;
}
}
int main(){
//declaring object
linkedlist l;
//taking input
cout<<"Enter no of nodes you want to insert\n";
int len;
cin>>len;
cout<<"Enter data\n";
for(int i=0;i<len;i++){
int tmp;
cin>>tmp;
l.insert_node(tmp);
}
//output data
cout<<"\nData you have entered is:\n";
l.display();
//deletion
cout<<"\n\nEnter no of nodes you want to delete\n";
int n=-1;
do{
if(n>len){
cout<<"\nERROR:Kindly enter valid input--";
}
cin>>n;
}
while(n>len);
while(n--){
cout<<"\n\nEnter node data you want to delete: ";
int count;
cin>>count;
l.delete_node(count);
}
//display after deletion
cout<<"\nData after deletion is:\n";
l.display();
return 0;
}