loveBabbar / CodeHelp-DSA-Busted-Series

This repo is creating providing students easy access to all the programs taught under Codehelp's DSA Busted Series.
3.35k stars 2.4k forks source link

Homework / Implementation of Stack Using Linked List #204

Open arzitmahajan opened 2 years ago

arzitmahajan commented 2 years ago

selftesting.zip

arzitmahajan commented 2 years ago

//Stack Implemented Using Linked List//

manvika-10 commented 2 years ago

include <bits/stdc++.h>

using namespace std;

struct StackNode { int data; StackNode *next; StackNode(int a) { data = a; next = NULL; } };

class MyStack { private: StackNode *top;

public: void push(int); int pop(); MyStack() { top = NULL; } };

int main() { int T; cin >> T; while (T--) { MyStack *sq = new MyStack();

    int Q;
    cin >> Q;
    while (Q--) {
        int QueryType = 0;
        cin >> QueryType;
        if (QueryType == 1) {
            int a;
            cin >> a;
            sq->push(a);
        } else if (QueryType == 2) {
            cout << sq->pop() << " ";
        }
    }
    cout << endl;
}

}

void MyStack ::push(int x) { StackNode *nw = new StackNode(x); nw -> next = top; top = nw; }

int MyStack ::pop() { int d; if(top==NULL) { return -1; } else { StackNode *t = top; d = top -> data; top = top -> next; delete t; return d; } }