jayati

Implement Stack using Linked List

Oct 11th, 2023
1,237
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.41 KB | None | 0 0
  1. //{ Driver Code Starts
  2. #include <bits/stdc++.h>
  3. using namespace std;
  4.  
  5. struct StackNode {
  6.     int data;
  7.     StackNode *next;
  8.     StackNode(int a) {
  9.         data = a;
  10.         next = NULL;
  11.     }
  12. };
  13.  
  14. class MyStack {
  15.   private:
  16.     StackNode *top;
  17.  
  18.   public:
  19.     void push(int);
  20.     int pop();
  21.     MyStack() { top = NULL; }
  22. };
  23.  
  24. int main() {
  25.     int T;
  26.     cin >> T;
  27.     while (T--) {
  28.         MyStack *sq = new MyStack();
  29.  
  30.         int Q;
  31.         cin >> Q;
  32.         while (Q--) {
  33.             int QueryType = 0;
  34.             cin >> QueryType;
  35.             if (QueryType == 1) {
  36.                 int a;
  37.                 cin >> a;
  38.                 sq->push(a);
  39.             } else if (QueryType == 2) {
  40.                 cout << sq->pop() << " ";
  41.             }
  42.         }
  43.         cout << endl;
  44.     }
  45. }
  46.  
  47. // } Driver Code Ends
  48.  
  49.  
  50. //Function to push an integer into the stack.
  51. void MyStack ::push(int x)
  52. {
  53.     // Your Code
  54.     if(top==NULL)
  55.     {
  56.         StackNode* n=new StackNode(x);
  57.         top=n;
  58.     }
  59.     else
  60.     {
  61.          StackNode* n=new StackNode(x);
  62.          StackNode* tmp=top;
  63.          n->next=top;
  64.          top=n;
  65.     }
  66. }
  67.  
  68. //Function to remove an item from top of the stack.
  69. int MyStack ::pop()
  70. {
  71.     // Your Code
  72.     int ans=-1;
  73.     if(top==NULL)
  74.     {
  75.         return -1;
  76.     }
  77.     else
  78.     {
  79.         ans=top->data;
  80.         top=top->next;
  81.     }
  82.     return ans;
  83. }
  84.  
Advertisement
Add Comment
Please, Sign In to add comment