Friday 21 September 2012

Insert node at kth position in single linked list

// insert node at kth position in single linked list

#include<conio.h>
#include<iostream.h>
struct node
{
int data ;
struct node *link;
};
void main()
{
clrscr();
int i,n,k;
struct node *temp,*start=NULL,*ptr,*ptr1;
temp=new node;
temp->data=10;
temp->link=NULL;
start=temp;
cout<<"Enter the data :=="<<endl;
for(i=1;i<=5;i++)
{
cin>>n;
temp=new node;
temp->data=n;
temp->link=start;
start=temp;
}
cout<<"Data is:---"<<endl;
for(temp=start;temp!=NULL;temp=temp->link)
{
cout<<temp->data<<endl;
}

cout<<"Enter the position where you want to insert the data:--"<<endl;
cin>>k;
  ptr=start;
for(i=1;i<k;i++)
{
ptr1=ptr;
ptr=ptr->link;
}
cout<<"Enter the data :--"<<endl;
cin>>n;
temp=new node;
temp->data=n;
temp->link=ptr;
ptr1->link=temp;


cout<<"Data is:---"<<endl;
for(temp=start;temp!=NULL;temp=temp->link)
{
cout<<temp->data<<endl;
}





getch();
}

No comments:

Post a Comment