Skip to content

Commit ccffab0

Browse files
committed
added linked list in cpp
1 parent 8678a21 commit ccffab0

File tree

1 file changed

+107
-0
lines changed

1 file changed

+107
-0
lines changed

linked_list_in_cpp/main.cpp

Lines changed: 107 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,107 @@
1+
#include "iostream.h"
2+
using namespace std;
3+
struct Node
4+
{
5+
int data;
6+
Node* link;
7+
};
8+
Node* A;
9+
void insert()
10+
{
11+
int n,p;
12+
cout<<"Enter the no to be Inserted:";
13+
cin>>n;
14+
cout<<"Enter the position:";
15+
cin>>p;
16+
Node* temp=new Node;
17+
if (p==1)
18+
{
19+
temp->link=A;
20+
temp->data=n;
21+
A=temp;
22+
return;
23+
}
24+
Node* temp2=A;
25+
for(int i=1;i<p-1;i++)
26+
{
27+
temp2=temp2->link;
28+
}
29+
temp->link=temp2->link;
30+
temp2->link=temp;
31+
temp->data=n;
32+
}
33+
void delet()
34+
{
35+
int p;
36+
cout<<"Enter the position of the element to be deleted:";
37+
cin>>p;
38+
Node* temp=A;
39+
if (p==1)
40+
{
41+
A=temp->link;
42+
temp=NULL;
43+
return;
44+
}
45+
Node* temp2=new Node;
46+
for(int i=1;i<p-1;i++)
47+
{
48+
temp=temp->link;
49+
}
50+
temp2=temp->link;
51+
temp->link=temp2->link;
52+
temp2=NULL;
53+
54+
}
55+
void display()
56+
{
57+
Node* temp=A;
58+
while(temp!=NULL)
59+
{
60+
cout<<"->"<<temp->data;
61+
temp=temp->link;
62+
}
63+
cout<<"\n"<<"---------------------------"<<"\n";
64+
}
65+
void rev()
66+
{
67+
Node* temp=A;
68+
Node* temp2=new Node;
69+
Node* prev=temp->link;
70+
while(prev!=NULL)
71+
{
72+
temp2=prev->link;
73+
prev->link=temp;
74+
temp=prev;
75+
prev=temp2;
76+
}
77+
A->link=NULL;
78+
A=temp;
79+
}
80+
void main()
81+
{
82+
A=NULL;
83+
while(1)
84+
{
85+
int ch;
86+
cout<<"Enter your choice:\n1-Insert\n2-Delete\n3-Display\n4-Reverse\n5-Exit\n->";
87+
cin>>ch;
88+
switch(ch)
89+
{
90+
case 1:
91+
insert();
92+
break;
93+
case 2:
94+
delet();
95+
break;
96+
case 3:
97+
display();
98+
break;
99+
case 4:
100+
rev();
101+
break;
102+
case 5:
103+
exit(0);
104+
}
105+
}
106+
}
107+

0 commit comments

Comments
 (0)