Menu Driven Program for Linked List operations: creation, traversing, insertion and deletion(Linked List)
Menu Driven Program for Linked List operations: creation, traversing, insertion and deletion(Linked List)
A menu driven program for linked list operations
a) Creation
of List
b)
Traversing of List
c) Insertion
at end, from beginning and given location.
d) Deletion at end, from beginning and any location.
#include <bits/stdc++.h>
using
namespace std;
struct Node
{
int data;
struct Node *next;
}*first=NULL;
void
create(int a[],int n)
{
struct Node *t,*last;
first=new Node;
first->data=a[0];
first->next=NULL;
last=first;
for(int i=1;i<n;i++)
{
t=new Node;
t->data=a[i];
t->next=NULL;
last->next=t;
last=t;
}
}
int
count(struct Node *p)
{
int c=0;
while(p)
{
c++;
p=p->next;
}
return c;
}
void
insert(int pos, int x)
{
if(pos>count(first) || pos<0)
return;
struct Node *t,*p=first;
t=new Node;
t->data=x;
t->next=NULL;
if(pos==0)
{
t->next=first;
first=t;
}
else{
for(int i=0;i<pos-1;i++)
p=p->next;
t->next=p->next;
p->next=t;
}
}
int
Delete(struct Node *p,int index)
{
struct Node *q;
int x=-1;
if(index<1 || index>count(first))
return x;
else if(index==1)
{
x=p->data;
first=p->next;
delete p;
return x;
}
else
{
for(int i=0;i<index-2;i++)
{
p=p->next;
}
q=p->next;
p->next=q->next;
x=q->data;
delete q;
return x;
}
}
void
display(struct Node *p)
{
while(p)
{
cout<<p->data<<"
";
p=p->next;
}
}
int main()
{
int a[500];
int option,n,pos,x,index,t;
do
{
cout<<"1. Create Linked
list"<<endl<<"2. Insert in Linked
list"<<endl<<"3. Delete
"<<endl<<"4. Display"<<endl<<"5.
Exit"<<endl;;
cout<<"Enter an
option"<<endl;
cin>>option;
switch(option)
{
case 1 :
{
cout<<"Enter no of
integers : "<<endl;
cin>>n;
cout<<"Enter the
numbers"<<endl;
for(int i=0;i<n;i++)
cin>>a[i];
create(a,n);
cout<<endl;
break;
}
case 2:
{
cout<<"Enter position to
insert an element : "<<endl;
cin>>pos;
cout<<"Enter element :
"<<endl;
cin>>x;
insert(pos,x);
cout<<endl;
break;
}
case 3:
{
cout<<"Enter position to
delete element : "<<endl;
cin>>index;
cout<<"Deleted element
is: "<<Delete(first,index);
cout<<endl;
break;
}
case 4:
{
cout<<"Displaying
elements :";
display(first);
cout<<endl;
break;
}
default:
cout<<"Exiting
program......"<<endl;
}
}while(option<=4);
return 0;
}
Creation Of Linked List
Recommended Posts
Comments
Post a Comment
Feel free to ask if you have any queries and if want any information . I feel happy to interact with you all and help you .