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
Give an example of run-time polymorphism/virtual functions.
Explain the differences between private, public and protected and give examples.
Can we overload operator in c++?
How can you link a c program with a c function?
What are vectors used for in c++?
What are the benefits of c++?
What is a manipulative person?
Explain differences between alloc() and free()?
What is do..while loops structure?
write a c++ program to create class student having datamember name,Roll_no,age,and branch intilcization all the member using constructor print the all the details on the screen.
Can we use this pointer in a class specific, operator-overloading function for new operator?
Is c++ a pure oop language?
What is the first name of c++?
What programming language should I learn first?
What is nested class in c++?