Hi All,
I have written reversible link list and pasting the code as below in c++. It works fine, please let me know if there are anything more that is required to make this more robust.
This is on a single link list.
#include "stdafx.h"
#include <iostream>
using namespace std;
class revlinklist
{
private:
struct revnode
{
char name[20];
int age;
float height;
revnode * link;
};
revnode * start;
public:
void addnode();
void addatbeg();
revlinklist();
~revlinklist();
void revdisplay();
void reverse();
void count();
};
revlinklist::revlinklist()
{
start= NULL;
}
void revlinklist::addnode()
{
start= new revnode;
cout<<"Enter the name of the person"<<endl;
cin>>start->name;
cout<<"Enter the age of the person"<<endl;
cin>>start->age;
cout<<"Enter the height of the person"<<endl;
cin>>start->height;
start->link = NULL;
}
void revlinklist::addatbeg()
{
revnode * temp;
temp = start;
start= new revnode;
cout<<"Enter the name of the person"<<endl;
cin>>start->name;
cout<<"Enter the age of the person"<<endl;
cin>>start->age;
cout<<"Enter the height of the person"<<endl;
cin>>start->height;
start->link = temp;
}
void revlinklist::count()
{
revnode *temp;
temp = start;
int c=0;
while(temp != NULL)
{
temp = temp->link;
c++;
}
cout<<"\n";
cout<<"The total number of nodes are:"<<c;
}
void revlinklist::revdisplay()
{
revnode *temp;
temp=start;
while(temp != NULL)
{
cout<<"The name of the person"<<" : "<<temp->name;
cout<<"\n";
cout<<"The age of the person"<<" : "<<temp->age;
cout<<"\n";
cout<<"The height of the person"<<" : "<<temp->height;
cout<<"\n";
temp=temp->link;
}
}
void revlinklist::reverse()
{
revnode *q, *r, *s;
q=start;
r=NULL;
while(q!=NULL)
{
s=r;
r=q;
q=q->link;
r->link=s;
}
start = r;
}
revlinklist::~revlinklist()
{
revnode *q;
while(start!=NULL)
{
q=start->link;
delete start;
start=q;
}
}
void main()
{
revlinklist l;
int revopt =0;
do {
//disp_list();
cout <<endl;
cout<<"1-Add the node" << endl;
cout<<"2-Add node at the beginning of the list" << endl;
cout<<"3-Number of nodes in the list" << endl;
cout<<"4-Display the list"<<endl;
cout<<"5-Reverse the list"<<endl;
cout<<"Enter the option of your choice"<<endl;
cin>>revopt;
switch(revopt)
{
case 1: l.addnode(); break;
case 2: l.addatbeg(); break;
case 3: l.count(); break;
case 4: l.revdisplay();break;
case 5: l.reverse();break;
default: cout<<"Enter the correct option";break;
}
} while(revopt !=0);
}