Breaking News
recent

WAP to insert an element in the beginning of linked list

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

void main()
{
node *start,*p,*beg;
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 the elements\t";
                cin>>p->data;
                j++;
cout<<"\nEnter your choice(y/n)?\t";
cin>>ch;
}while(ch=='y'||ch=='Y');
p->next='\0';

cout<<"\nElements for nodes are";
p=start;
while(p!=0)
{
  cout<<"\t"<<endl<<p->data;
  p=p->next;
}
cout<<endl;
cout<<"\nNumber of nodes are "<<j;
getch();

cout<<"\n-----------------INSERTION AT THE BEGINNING---------";
beg=new node;
cout<<"\nEnter Element for new node ";
cin>>beg->data;
beg->next=start;
start=beg;
cout<<"\nElement for nodes is";
p=start;
j=0;


while(p!=0)
{
 cout<<"\t"<<endl<<p->data;
  j++;
  p=p->next;
}
cout<<endl;
cout<<"\nNumber of nodes = "<<j;
getch();

}

Output:


Unknown

Unknown

No comments:

Post a Comment

Powered by Blogger.