-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlinkedlist.cpp
More file actions
169 lines (168 loc) · 2.28 KB
/
Copy pathlinkedlist.cpp
File metadata and controls
169 lines (168 loc) · 2.28 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
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
#include<iostream>
using namespace std;
class linked_list
{
struct node
{
int item;
node *next;
};
node *start;
public:
linked_list()
{
start=NULL;
}
void insert(int data);
void delete_i(int i);
int count(int data);
void display();
};
void linked_list::insert(int data)
{
node *t=new node;
t->item=data;
if(start==NULL)
{
t->next=start;
start=t;
}
else
{
if(start->item>=data)
{
t->next=start;
start=t;
}
else
{
node *n=start;
node *m;
while(n!=NULL)
{
if(n->item<data)
m=n;
n=n->next;
}
t->next=m->next;
m->next=t;
}
}
}
void linked_list::delete_i(int i)
{
if(start==NULL)
cout<<"List is empty"<<endl;
else
{
int count=0;
node *n=start;
while(n!=NULL)
{
count++;
n=n->next;
}
if(i>count)
cout<<i<<"th element dose not exist"<<endl;
else
{
n=start;
if(i==1)
{
cout<<"Item Deleted = "<<n->item<<endl;
start=start->next;
delete n;
}
else
{
node *t;
for(int j=1;j<i;j++)
{
t=n;
n=n->next;
}
cout<<"Item Deleted = "<<n->item<<endl;
t->next=n->next;
delete n;
}
}
}
}
void linked_list::display()
{
if(start==NULL)
cout<<"List is empty"<<endl;
else if(start->next==NULL)
{
cout<<start->item<<endl;
}
else
{
node *t=start;
while(t!=NULL)
{
cout<<t->item<<" ";
t=t->next;
}
cout<<endl;
}
}
int linked_list::count(int data)
{
if(start==NULL)
return 0;
else
{
node *t=start;
int c=0;
while(t!=NULL)
{
if(t->item==data)
c++;
t=t->next;
}
return c;
}
}
int choice()
{
int i;
cout<<"1.Insert\n2.Delete ith Node\n3.Count Number of occurrences of a number\n4.Display list\n5.Exit"<<endl;
cout<<"Enter your choice"<<endl;
cin>>i;
return i;
}
int main()
{
linked_list l;
int n;
while(1)
{
switch(choice())
{
case 1:
cout<<"Enter a number"<<endl;
cin>>n;
l.insert(n);
break;
case 2:
cout<<"Enter i(i starting from 1)"<<endl;
cin>>n;
l.delete_i(n);
break;
case 3:
cout<<"Enter a number"<<endl;
cin>>n;
cout<<n<<" occurred "<<l.count(n)<<" times in the list"<<endl;
break;
case 4:
l.display();
break;
case 5:
cout<<"Thank You"<<endl;
exit(0);
default:
cout<<"Invalid choice"<<endl;
}
}
}