Advertisement
Eternoseeker

Stack basic push and pop

Nov 15th, 2022
66
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.09 KB | Source Code | 0 0
  1. #include <iostream>
  2. using namespace std;
  3.  
  4. struct node{
  5.     int data;
  6.     node *next;
  7. };
  8.  
  9. class stack{
  10.     node *top = new node;
  11. public:
  12.     stack(){
  13.         top = NULL;
  14.     }
  15.     void push(int v){
  16.         node *nn = new node;
  17.         nn -> data = v;
  18.         nn -> next = top;
  19.         top = nn;
  20.     }
  21.  
  22.     int pop(){
  23.         if(top == NULL){
  24.             cout << "Stack is empty " << endl;
  25.             return 0;
  26.         }
  27.         else {
  28.             node *t = top;
  29.             int val = top-> data;
  30.             top = top -> next;
  31.             free(t);
  32.             return val;
  33.         }
  34.     }
  35.  
  36.     void display(){
  37.         node *t=top;
  38.         while(t!=NULL){
  39.             cout << t->data <<" -> ";
  40.             t=t->next;
  41.         }
  42.         cout<<"NULL\n";
  43.     }
  44. };
  45.  
  46. int main(){
  47.     stack s;
  48.     int ch = 10;
  49.     while(ch != 0){
  50.         cout << "Enter your choice" << endl;
  51.         cout << "1: Push an element " << endl;
  52.         cout << "2: Pop an element " << endl;
  53.         cout << "0: Exit " << endl;
  54.         cin >> ch;
  55.         switch(ch){
  56.         case 1:
  57.             int value;
  58.             cout << "Enter value to push" << endl;
  59.             cin >> value;
  60.             s.push(value);
  61.             s.display();
  62.             break;
  63.         case 2:
  64.             cout << "Popped element: " << s.pop() << endl;
  65.             s.display();
  66.             break;
  67.         }
  68.     }
  69.     return 0;
  70. }
  71.  
Tags: snippets
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement