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
What is the keyword auto for?
How many different levels of pointers are there?
What is #include cmath?
Why do we use setw in c++?
How many standards of c++ are there?
What are the uses of typedef in a program?
What are special characters c++?
How would you differentiate between a pre and post increment operators while overloading?
If a base class is an adt, and it has three pure virtual functions, how many of these functions must be overridden in its derived classes?
What is meant by const_cast?
What does getch() do according to the ANSI C++ standard a) Reads in a character b) Checks the keyboard buffer c) Nothing in particular (Its not defined there)
What is the most common mistake on c++ and oo projects?
Differentiate between a constructor and a method in C++.
Differentiate between structure and class in c++.
Function can be overloaded based on the parameter which is a value or a reference. Explain if the statement is true.