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 a string example?
What are c++ templates used for?
What is the maximum value of a unsigned char a) 255 b) 256 c) 128
What are stacks? Give an example where they are useful.
Search for: what is pair in c++?
What is the best c++ compiler for windows 10?
If you hear the cpu fan is running and the monitor power is still on, but you did not see anything show up in the monitor screen. What would you do to find out what is going wrong?
Will c++ be replaced?
What is c++ w3school?
What is a dangling pointer in c++?
What data encapsulation is in c++?
What is new in c++?
Define a nested class.
Which programming language is best?
What do you understand by pure virtual function? Write about its use?