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

There are 100 students in a class. The management keep information in two tables. Those two tables are given like Roll no Name Age 001 ABC 15 002 XYZ 14 and Roll No Subject Marks 001 Math 75 001 Physics 55 002 Math 68 001 Hindi 69 They want the information like this Roll No Name Hindi Physics Math Total 001 ABC 69 55 75 199 002 XYZ 68 74 84 226 And Roll No Suject Highest 001 Math 98 007 Physics 84 021 Hindi 74 All 275 All information is kept in structure in main memory. You have to find last two tables.

2526


What are files in c++?

585


what are the iterator and generic algorithms.

1475


Assume studentNames and studentIDs are two parallel arrays of size N that hold student data. Write a pseudocode algorithm that sorts studentIDs array in ascending ID number order such that the two arrays remain parallel.

1710


What is a wchar_t in c++?

575






Is sorted c++?

564


What is the most common mistake on c++ and oo projects?

512


Explain public, protected, private in c++?

561


Explain polymorphism?

577


What is the difference between #import and #include in c++?

588


Explain linear search.

618


How would you implement a substr() function that extracts a sub string from a given string?

557


When the constructor of a base class calls a virtual function, why doesn't the override function of the derived class gets called?

562


What is the difference between C and CPP?

624


Is empty stack c++?

513