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

Mention the ways in which parameterized can be invoked. Give an example of each.

767


What is the use of seekg in c++?

781


How can you link a c++ program to c functions?

815


What does h mean in maths?

812


Suppose that data is an array of 1000 integers. Write a single function call that will sort the 100 elements data [222] through data [321].

1179






Can we make any program in c++ without using any header file and what is the shortest program in c++.

796


In int main(int argc, char *argv[]) what is argv[0] a) The first argument passed into the program b) The program name c) You can't define main like that

817


Can java be faster than c++?

853


What is setfill c++?

876


Explain operator overloading.

796


What is cin clear () in c++?

829


total amount of milk produced each morning and then calculates and outputs the number of cartons needed for this milk , the cost of producing the milk and the profit from producing this milk.

2271


How can you link a c program with a c function?

753


Why we use #include iostream in c++?

752


How would you differentiate between a pre and post increment operators while overloading?

835