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

Give an example of run-time polymorphism/virtual functions.

550


What do you mean by function and operator overloading in c++?

603


What do you mean by ‘void’ return type?

598


What is runtime polymorphism in c++?

578


What is algorithm in c++ programming?

581






What is static class data?

565


What is the use of seekg in c++?

591


What is polymorphism and its type in c++?

578


What does floor mean in c++?

570


What is the use of "new" operator?

651


How to declaring variables in c++?

649


What is a local reference?

663


what are the events occur in intr activated on interrupt vector table

1172


What are c++ variables?

528


Can we get the value of ios format flags?

655