Write a program to reverse a linked list?

Answer Posted / ajaypal singh badgujar

#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 ?    0 Yes 2 No



Post New Answer       View All Answers


Please Help Members By Posting Answers For Below Questions

What is a constructor and how is it called?

587


Is it possible to get the source code back from binary file?

706


What is algorithm in c++ programming?

585


What is c++ course?

574


Should I learn c or c++ first?

562






How many types of modularization are there in c++?

562


Should you pass exceptions by value or by reference?

692


What is namespace std; and what is consists of?

659


What is c++ in english?

572


Explain the differences between private, public and protected and give examples.

564


Which software is used to run c++ program?

546


How can an improvement in the quality of software be done by try/catch/throw?

586


What is nested class in c++?

514


List the features of oops in c++?

569


What are c++ redistributables?

554