#include<iostream.h>
#include<conio.h>
#include<stdlib.h>
struct link
{
int data;
struct link *next;
};
class list
{
private:
struct link *start,*temp,*ptr,*curr;
public:
list()
{
cout<<"LinkedList is created"<<endl;
start=NULL;
}
void menu();
void insertnode();
void deletenode();
void display();
};
void list::menu()
{
int ch;
do
{
cout<<endl;
cout<<"Linked list"<<endl
<<"1.Insert"<<endl
<<"2.Delete"<<endl
<<"3.Display"<<endl
<<"4.Exit"<<endl;
cout<<"Enter your choice : ";
cin>>ch;
switch(ch)
{
case 1: insertnode();
break;
case 2: deletenode();
break;
case 3: display();
break;
case 4: exit(0);
break;
default: cout<<"Sorry! invalid choice"<<endl;
}
}while(ch!=4);
}
void list::insertnode()
{
cout<<"Enter an Element to insert : ";
int v;
cin>>v;
temp=new link;
temp->data=v;
cout<<"1.At beginning "<<endl
<<"2.At particular position"<<endl
<<"3.At ending"<<endl;
int ch;
cout<<"Enter your choice : ";
cin>>ch;
switch(ch)
{
case 1: if(start==NULL)
{
start=temp;
start->next=NULL;
return;
}
temp->next=start;
start=temp;
break;
case 2: cout<<"Enter the position of the element :";
int n;
cin>>n;
int ctr=1;
curr=start;
while(ctr!=n)
{
ptr=curr;
curr=curr->next;
ctr++;
}
ptr->next=temp;
temp->next=curr;
break;
case 3: curr=start;
while(curr->next!=NULL)
{
curr=curr->next;
}
curr->next=temp;
temp->next=NULL;
break;
default: cout<<"Sorry! invalid choice"<<endl;
}
}
void list::deletenode()
{
cout<<"1.At beginning "<<endl
<<"2.At particular position"<<endl
<<"3.At ending"<<endl;
int ch1;
cout<<"Enter your choice : ";
cin>>ch1;
switch(ch1)
{
case 1: if(start==NULL)
{
cout<<"The list is empty";
return;
}
temp=start;
start=start->next;
delete temp;
break;
case 2: cout<<"Enter the position to delete : ";
int n;
cin>>n;
int ctr=1;
curr=start;
while(ctr!=n)
{
ptr=curr;
curr=curr->next;
ctr++;
}
ptr->next=curr->next;
delete curr;
break;
case 3: curr=start;
while(curr->next)
{
ptr=curr;
curr=curr->next;
}
ptr->next=NULL;
delete curr;
break;
default: cout<<"Sorry! invalid choice"<<endl;
}
}
void list::display()
{
curr=start;
while(curr!=NULL)
{
cout<<" "<<curr->data;
curr=curr->next;
}
}
void main()
{
clrscr();
list l;
l.menu();
getch();
}
No comments:
Post a Comment