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

Which programming language is best?

545


If dog is a friend of boy and boy is a friend of house, is dog a friend of house?

545


What is the use of c++ programming language in real life?

558


What is binary search in c++?

561


What is the use of :: operator in c++?

593






What are multiple inheritances (virtual inheritance)? What are its advantages and disadvantages?

561


What is ios :: in in c++?

629


What is polymorphism in c++? Explain with an example?

603


What is friend class in c++ with example?

494


What is the use of vtable?

663


Is c++ free?

577


Is turbo c++ free?

613


We use library functions in the program, in what form they are provided to the program?

590


Distinguish between a # include and #define.

641


What are the storage qualifiers?

659