Breaking News
recent

WAP to insert an element at any location in linked list

#include<iostream.h>
#include<conio.h>
class node
{                     
public:
char data;
node *next;
};

void main()
{
                node *start, *p, *current;
                char ch;
                int j=0;
                clrscr();
                start='\0';
do
                {
                if(start=='\0')
                                {
                                start=new node;
                                p=start;
                                }
                else
                                {
                                p->next=new node;
                                p=p->next;
                               
}
cout<<"\nEnter data  ";
cin>>p->data;
j++;
cout<<"\nEnter choice y/n?";
cin>>ch;
}
while(ch=='Y'||ch=='y');
p->next='\0';
cout<<"\nData for nodes  ";
p=start;
while(p!='\0')
                {
                cout<<endl<<p->data;
                p=p->next;
                }
cout<<endl<<"No. of nodes  "<<j<<endl;
cout<<"\n--------------Insertion of element at any location---------------------";
int loc;
int count=1;
cout<<"\nEnter location where you want to enter node  ";
cin>>loc;
if(loc<=j)
{     
current=new node;
                cout<<"\nEnter data  : ";
                cin>>current->data;
p=start;
while(p!='\0' && count<loc-1)
                { p=p->next;
                count++;
                }
current->next=p->next;
                p->next=current;
cout<<"Data in list is :"<<endl;
p=start;
while(p!='\0')
                { cout<<endl<<p->data;
                  p=p->next;
                }
 }
else
cout<<"\nEnter valid loction!!";
 }
getch();
 }

Output:


Unknown

Unknown

No comments:

Post a Comment

Powered by Blogger.