Our Feeds

Saturday, 26 December 2015

AJITH KP

Implementation of Stack using Singly Linked List in C++

Hi GuyZ,
     Implementation of stack is another important problem in Data Structures paper. Implementation of stack using Singly Linked List can be another problem you may have to solve.


Solution

#include <iostream>
using namespace std;
struct node{
 int data;
 node *link = NULL;
};
class stack{
 node *root;
public:
 stack(){
  root = NULL;
 }
 void push(){
  node *nn = new node;
  cout<<"Enter data: ";
  cin>>nn->data;
  nn->link = root;
  root = nn;
  cout<<"Data "<<nn->data<<" pushed to stack...";
 }
 void pop(){
  node *nn;
  if(root){
   nn = root;
   root = root->link;
   cout<<"Data "<<nn->data<<" is popped from stack...";
   delete(nn);
  }
  else{
   cout<<"Error: Stack is empty...";
  }
 }
 void empty(){
  if(root){
   cout<<"Stack is Not Empty...";
  }
  else{
   cout<<"Stack is Empty...";
  }
 }
 void show(){
  node *tmp = root;
  cout<<"Stack: ";
  if(root){
   while(tmp){
    cout<<tmp->data<<" ";
    tmp = tmp->link;
   }
  }
  else{
   cout<<"Empty...";
  }
 }
};
class stackops{
 stack s;
public:
 void menu(){
  int op = 0;
  cout<<"\t\t\tMENU\n1. PUSH\n2. POP\n3. Status\n4. Show\n5. Exit";
  while(op!=5){
   cout<<"\nOption: ";
   cin>>op;
   switch(op){
    case 1:
     s.push();
     break;
    case 2:
     s.pop();
     break;
    case 3:
     s.empty();
     break;
    case 4:
     s.show();
     break;
    case 5:
     break;
    default:
     cout<<"Error: Try again...";
     break;
   }
  }
 }
};
int main()
{
 stackops s;
 s.menu();
 return 0;
}