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

Will c++ be replaced?

804


Explain function overloading and operator overloading.

797


Define a nested class.

806


How many standards of c++ are there?

822


Explain what data encapsulation is in c++?

763






Explain object slicing in c++?

766


What are stacks?

796


What do you mean by storage classes?

1101


Explain container class.

910


Why was c++ made?

824


What are the extraction and insertion operators in c++?

738


Explain the uses oof nested class?

848


What is the difference between reference and pointer?

817


what are the iterator and generic algorithms.

1872


How do you define a class in c++?

805