A program to reverse a Link List.

 

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

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

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

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

void reverse()
{
if(start==NULL)
cout<<"\nThere is no data present in the Link List.\n";
else
{
x=start;
new_start=x->link;
x->link=NULL;
while(new_start!=NULL)
{
y=x;
x=new_start;
new_start=new_start->link;
x->link=y;
}
start=x;
}
}

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

void main()
{
 clrscr();

 int ch;

 do
  {
   cout<<"1. Create a node."<<endl;
   cout<<"2. Reverse the Link List."<<endl;
   cout<<"3. Display Link List."<<endl;
   cout<<"4. Exit."<<endl;
   cout<<"Enter your choice: ";
   cin>>ch;

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

 

< Back