forked from Soumojitshome2023/DSA_Hacktoberfest_2023
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLinkedList
170 lines (164 loc) · 3.55 KB
/
LinkedList
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
#include<iostream>
using namespace std;
class Node
{
public:
int data;
Node *next;
Node(int x)
{
data=x;
next=NULL;
}
};
class LinkedList
{
public:
int count=0;
Node *head=NULL;
void insertbegin(int x)
{
Node *curr=new Node(x);
count++;
if(head==NULL)
head=curr;
else
{
curr->next=head;
head->next=curr;
head=curr;
}
cout <<"\nNo of nodes="<<count<<"\n";
}
void insertend(int n)
{
Node *curr=new Node(n);
if(head==NULL)
head=curr;
else
{
int i=1;
Node *temp=head;
while(i<count)
temp=temp->next;
curr->next=head;
temp->next=curr;
count++;
}
}
void delbeg()
{
if(head==NULL)
cout<<"Empty list";
else
{
Node *temp1=head;
int i=1;
while(i<count)
{
temp1=temp1->next;
}
Node *temp=head;
head=head->next;
temp1->next=head;
delete(temp);
count--;
}
}
void delend()
{
if (head == NULL)
{
cout << "Empty list" << endl;
return;
}
else
{
Node *temp = head;
int i=1;
while(i<count-1)
{
temp=temp->next;
}
Node *temp1=temp->next;
temp->next=head;
delete(temp1);
}
}
void delpos(int pos)
{
int count;
if(head==NULL)
cout<<"Empty List";
else
{
Node *temp=head;
count=1;
while(count<pos-1)
{
temp=temp->next;
count++;
}
Node *temp1=temp->next;
temp->next=temp->next->next;
delete(temp1);
}
}
void display()
{
Node *temp=head;
if(head==NULL)
cout<<"Empty List";
else
{
int i=1;
while(i<count)
{
cout<<temp->data<<endl;
temp=temp->next;
}
}
}
};
int main()
{
LinkedList mylist;
int choice,n,pos;
do{
cout<<"1.Enter value at the beginning:"<<endl;
cout<<"2.Enter value at the end:"<<endl;
cout<<"3.Delete from beginning:"<<endl;
cout<<"4.Display the list:"<<endl;
cout<<"5.Delete from end:"<<endl;
cout<<"6.Delete from position:"<<endl;
cout<<"Enter your choice"<<endl;
cin>>choice;
switch(choice)
{
case 1:
cout<<"Input Element to insert";
cin>>n;
mylist.insertbegin(n);
break;
case 2:
cout<<"Input element to insert";
cin>>n;
mylist.insertend(n);
break;
case 3:
mylist.delbeg();
break;
case 5:
mylist.delend();
break;
case 4:
mylist.display();
break;
case 6:
cout<<"Enter position to be delete:"<<endl;
cin>>pos;
mylist.delpos(pos);
break;
}
}while(choice<=7);
}