splash365

stack (using linked list)

Jan 8th, 2021 (edited)
172
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.34 KB | None | 0 0
  1. #include<bits/stdc++.h>
  2.  
  3. using namespace std;
  4.  
  5. struct Stack
  6. {
  7.     int data;
  8.     Stack *next;
  9. };
  10.  
  11. Stack *top = NULL;
  12.  
  13. Stack *StackNode(int val)
  14. {
  15.     Stack *newNode = new Stack();
  16.     newNode->data = val;
  17.     newNode->next = NULL;
  18.     return newNode;
  19. }
  20.  
  21. bool isEmpty()
  22. {
  23.     if(top == NULL) return true;
  24.     return false;
  25. }
  26.  
  27. void push(int val)
  28. {
  29.     Stack *newNode = StackNode(val);
  30.     if(isEmpty()) top = newNode;
  31.     else
  32.     {
  33.         newNode->next = top;
  34.         top = newNode;
  35.     }
  36. }
  37.  
  38. void pop()
  39. {
  40.     if(isEmpty()) cout<<"Can't pop from an empty stack\n";
  41.     else
  42.     {
  43.         Stack *cur = top;
  44.         top = top->next;
  45.         free(cur);
  46.     }
  47. }
  48.  
  49. int Top()
  50. {
  51.     if(isEmpty()) cout<<"Stack is empty!\n";
  52.     else
  53.     {
  54.         return top->data;
  55.     }
  56. }
  57.  
  58. void printStack()
  59. {
  60.     if(isEmpty()) cout<<"Stack is empty!\n";
  61.     else
  62.     {
  63.         while(top != NULL)
  64.         {
  65.             cout<<Top()<<" ";
  66.             pop();
  67.         }
  68.     }
  69.     cout<<endl;
  70. }
  71.  
  72.  
  73.  
  74. int main()
  75. {
  76.     cout<<"Enter the number of elements: ";
  77.     int n;
  78.     cin>>n;
  79.  
  80.     for(int i=0; i<n; i++)
  81.     {
  82.         int val;
  83.         cin>>val;
  84.         push(val);
  85.     }
  86.     pop();
  87.     printStack();
  88.     int t;
  89.     if(!isEmpty())
  90.     {
  91.         t = Top();
  92.         cout<<t;
  93.     }
  94. }
  95.  
  96.  
  97.  
  98.  
  99.  
  100.  
  101.  
  102.  
  103.  
  104.  
  105.  
  106.  
  107.  
  108.  
  109.  
Add Comment
Please, Sign In to add comment