Write a program to reverse a linked list?

Answer Posted / jithin

#include<iostream>
using namespace std;
class Link;
class Node
{
int value;
Node * next;
friend class Link;
};
class Link
{
Node * start;
public:
Link();
void add();
void display();
void reverse();
};

Link::Link()
{
start=NULL;
}

void Link::add()
{
int value;
Node * node=new Node;
cout<<"Enter the number:";
cin>>node->value;
node->next=NULL;
if(start==NULL)
{
start=node;
}
else
{
Node * temp=start;
while(temp->next!=NULL)
{
temp=temp->next;
}
temp->next=node;
}


}

void Link::display()
{
Node * temp=start;
while(temp->next!=NULL)
{
cout<<temp->value<<"-->";
temp=temp->next;
}
cout<<temp->value<<"\n";
}

void Link::reverse()
{
Node * temp,* temp1,* temp2;
temp=start;
temp2=NULL;
while(temp)
{
temp1=temp->next;
if(temp1==NULL)
start=temp;
temp->next=temp2;
temp2=temp;
temp=temp1;
}

}
main()
{
int i=0;

Link link;
while(i<6)
{
link.add();
i++;
}
link.display();
link.reverse();
cout<<"======================After reversing\n";
link.display();
}

Is This Answer Correct ?    8 Yes 0 No



Post New Answer       View All Answers


Please Help Members By Posting Answers For Below Questions

What are keywords in c++?

853


What is the use of endl in c++?

808


Where are setjmp and longjmp used in c++?

859


What is type of 'this' pointer? Explain when it is get created?

798


How a pointer differs from a reference?

1006


What are the rules about using an underscore in a c++ identifier?

864


What is insertion sorting?

878


Should I learn c or c++ first?

883


Do you know the use of vtable?

883


What is static class data?

806


If you push the numbers (in order) 1, 3, and 5 onto a stack, which pops out first a) 1 b) 5 c) 3

1112


Is c++ harder than java?

819


What is double in c++?

836


What is a class template in c++?

817


What is the C-style character string?

845