C++ program to reverse a linked list using three pointers
C++ program to reverse a linked list
#include<iostream>
#include<conio.h>
using namespace std;
struct links
{
int data;
links *next;
};
class linkedlist
{
links *start;
public:
void create();
void reverse();
void display();
};
void linkedlist::reverse()
{
links *temp1,*temp2,*temp3;
temp1=start;
temp2=NULL;
while(temp1!=NULL)
{
temp3=temp2;
temp2=temp1;
temp1=temp1->next;
temp2->next=temp3;
}
start=temp2;
}
void linkedlist::create()
{
int take;
links *temp;
char ch;
cout<<"Enter the element ";
cin>>take;
start=new links;
start->data=take;
start->next=NULL;
temp=start;
cout<<"Want to enter more elements (Y/N)\n";
ch=getch();
while(ch!='n'&&ch!='N')
{
cout<<"Enter the element ";
cin>>take;
temp->next=new links;
temp=temp->next;
temp->data=take;
temp->next=NULL;
cout<<"Want to enter more elements (Y/N)\n";
ch=getch();
}
}
void linkedlist::display()
{
links *temp=start;
while(temp!=NULL)
{
cout<<temp->data<<"-> ";
temp=temp->next;
}
cout<<"NULL\n";
}
int main()
{
linkedlist revert;
cout<<"Create a list "<<endl;
revert.create();
cout<<"\nBefore reversing linked list\n ";
revert.display();
revert.reverse();
cout<<"\nAfter reversing linked list\n";
revert.display();
return 0;
}
#include<conio.h>
using namespace std;
struct links
{
int data;
links *next;
};
class linkedlist
{
links *start;
public:
void create();
void reverse();
void display();
};
void linkedlist::reverse()
{
links *temp1,*temp2,*temp3;
temp1=start;
temp2=NULL;
while(temp1!=NULL)
{
temp3=temp2;
temp2=temp1;
temp1=temp1->next;
temp2->next=temp3;
}
start=temp2;
}
void linkedlist::create()
{
int take;
links *temp;
char ch;
cout<<"Enter the element ";
cin>>take;
start=new links;
start->data=take;
start->next=NULL;
temp=start;
cout<<"Want to enter more elements (Y/N)\n";
ch=getch();
while(ch!='n'&&ch!='N')
{
cout<<"Enter the element ";
cin>>take;
temp->next=new links;
temp=temp->next;
temp->data=take;
temp->next=NULL;
cout<<"Want to enter more elements (Y/N)\n";
ch=getch();
}
}
void linkedlist::display()
{
links *temp=start;
while(temp!=NULL)
{
cout<<temp->data<<"-> ";
temp=temp->next;
}
cout<<"NULL\n";
}
int main()
{
linkedlist revert;
cout<<"Create a list "<<endl;
revert.create();
cout<<"\nBefore reversing linked list\n ";
revert.display();
revert.reverse();
cout<<"\nAfter reversing linked list\n";
revert.display();
return 0;
}
No comments:
Post a Comment