A program to Insert a node in a Link List.

 

#include<iostream.h>
#include<conio.h>

struct node
{
int data;
node* link;
};

node *start=NULL,*x,*y;

void begin()
{
if(start==NULL)
{
start=new node;
cout<<"\nEnter data: ";
cin>>start->data;
start->link=NULL;
cout<<endl;
}
else
{
x=new node;
cout<<"Enter data: ";
cin>>x->data;
x->link=start;
start=x;
cout<<endl;
}
}

void end()
{
if(start==NULL)
{
start=new node;
cout<<"\nEnter data: ";
cin>>start->data;
start->link=NULL;
cout<<endl;
}
else
{
x=start;
while(x->link!=NULL)
x=x->link;
y=new node;
cout<<"\nEnter data: ";
cin>>y->data;
y->link=NULL;
x->link=y;
x=y;
cout<<endl;
}
}

void mid()
{
int val;

if(start==NULL)
{
cout<<"\nThere is no element present in the Link List.\n\n";
}
else
{
cout<<"\nEnter value after which insertion is required: ";
cin>>val;

x=start;

while(x!=NULL && x->data!=val)
x=x->link;

if(x->data==val)
{
y=new node;
cout<<"\nEnter data: ";
cin>>y->data;
y->link=x->link;
x->link=y;
cout<<endl;
}
else
cout<<"\nData not present.\n";
}
}

void display()
{
x=start;
cout<<"\nLink list as follows: ";
while(x!=NULL)
{
cout<<x->data<<" ";
x=x->link;
}
cout<<endl<<endl;
}

void main()
{
 clrscr();

 int ch;

 do
  {
   cout<<"1. Insert at begining."<<endl;
   cout<<"2. Insert at end."<<endl;
   cout<<"3. Insert in the middle."<<endl;
   cout<<"4. Display Link List."<<endl;
   cout<<"5. Exit."<<endl;
   cout<<"Enter your choice: ";
   cin>>ch;

   switch(ch)
    {
     case 1: {
                 begin();
                 break;
                }
     case 2: {
                 end();
                 break;
                }
     case 3: {
                 mid();
                 break;
                }
     case 4: {
                 display();
                 break;
                }
     case 5: {
                 break;
                }
     default:{
                 cout<<"\nWrong choice entered.\n\n";
                }
    }
  }
 while(ch!=5);
}

 

< Back