Monday, 12 December 2016

Write A Program To Reverse The Linkdlist Using Stack In C++.

QUESTION : Write A Program To Reverse The Singly Linkedlist  Using Stack In C++.

COPY CODE:

  #include<iostream>
#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
#include<stack>
using namespace std;
struct node
{
int data;
struct node *next;
}*root=NULL;
void createnode()
{
int x;
struct node *temp=(struct node*)malloc(sizeof(struct node)); //memory allocation
cout<<"enetr the data";
cin>>x;
temp->data=x;
temp->next=root;
root=temp;
}
 
 void deletenode()     // delete node from begning
 {
  if(root==NULL)
  {
  cout<<"linked list is empty";
   return;
 }
struct node *temp=root;
root=temp->next;
free(temp);
   
 }
 void print()  //for display the list
 {
  struct node *temp;
  temp=root;
  while(temp!=NULL)
  {
  cout<<temp->data<<"->";
  temp=temp->next;
}
 }
 void reverse()
 {
  if(root==NULL)
  {
  return;
}
   stack<struct node*> s; //create stack template for struct node type 
   struct node *temp;
   temp=root;
   while(temp!=NULL) // loop to push the refrence of node
   {
    s.push(temp);
    temp=temp->next;
   }
   temp=s.top();
   root=temp;
   s.pop();
   while(!s.empty())  // loop to poping the refrence of  node
   {
    temp->next=s.top();
    s.pop();
    temp=temp->next;
   }
   temp->next=NULL;
   
}
int main()
{
for(int i=0;i<5;i++)
createnode();
print();
reverse();
cout<<"\n after reverse of linked list";
print();
return 0;
}

www.programmingwithbasics.com

No comments:
Write comments

Recommended Posts × +