All Programs are Written and Compiled in Dev C++. So, it may generate some error in case of other compilers and may need some modifications in program. Download Dev C++

Friday, 28 March 2014

Insertion In A Linked List At Some Location

//Insertion At Location

#include<iostream>
using namespace std;
struct node
{
 int info;
 node *link;
};
int main()
{
 node *start,*p,*loc,*temp;
 start=p=NULL;
 //Creating Linked List
 int n;
 cout<<"Press [0] to Exit :: Input Elements To List :";
 do
 {
    cin>>n;
  if(n)
  {
     temp=new node;
     temp->info=n;
     temp->link=NULL;
     if(start==NULL)
 start=temp;
     else
 p->link=temp;
     p=temp;
    }
 }while(n);
 //printing nodes
 p=start;
 cout<<"Created Nodes are : ";
 while(p)
 {
  cout<<p->info<<" ";
  p=p->link;
 }
///////////////////////////////
cout<<"\nEnter item to insert ";
int item;
cin>>item;
cout<<"Place where to Insert :";
int k;
cin>>k;
loc=NULL;
p=start;
 for(int i=1;i<=k-1;i++)
 {
p=p->link;
loc=p;
 }
temp=new node;
temp->info=item;
 if(loc==NULL)
 {
temp->link=start;
start=temp;
 }
 else
 {
temp->link=loc->link;
loc->link=temp;
 }
//printing
 p=start;
 cout<<"List After Insertion : ";
 while(p!=NULL)
 {
  cout<<p->info<<" ";
  p=p->link;
 }
return 0;
}

No comments:

Post a Comment