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

Why is standard template library used?

817


What is scope operator in c++?

842


What programming language should I learn first?

848


To what does “event-driven” refer?

842


What are the differences between new and malloc?

838


What are the unique features of C++.

808


What is the type of 'this' pointer?

812


What is time_t c++?

832


What is iostream in c++ used for?

757


What are compilers in c++?

867


What are activex and ole?

798


What are the advantages of prototyping?

825


What is the difference between prefix and postfix versions of operator++()?

848


What will the line of code below print out and why?

547


What is an iterator class in c++?

890