maneedhar
12/26/2019 - 7:27 PM

Stack Implementation

#include<bits/stdc++.h>
using namespace std;

class node {
public:
    int data;
    node* next;
    node (){
        data = 0;
        next = NULL;
    }
    node (int x){
        data = x;
        next = NULL;
    }
};

class Stack{
public:
    node* top;
    Stack() {
        top = NULL;
    }

    void pop(){
        if (top == NULL){
            cout<<"error"<<endl;
        }
        node* temp = top;
        top = temp -> next;
    }

    void push(int x){
        node* n = new node(x);
        if (top == NULL){
            top = n;
        }else{
            n->next = top;
            top = n;
        }
    }

    void print(){
        if (top == NULL){
            cout<<"Empty"<<endl;
        }else{
            node* temp = top;
            while (temp != NULL){
                cout<<temp->data<<" ";
                temp = temp->next;
            }
        }
        cout<<endl;
    }

};

int main(){
    Stack s;
    s.push(3);
    s.print();
    s.push(4);
    s.push(5);
    s.print();
    s.pop();
    s.print();
    return 0;
}