Hello, OnlineGDB Q&A section lets you put your programming query to fellow community users. Asking a solution for whole assignment is strictly not allowed. You may ask for help where you are stuck. Try to add as much information as possible so that fellow users can know about your problem statement easily.

Write a C++program to do the following ADT stack, que, pop, linked list

+5 votes
asked Feb 25, 2020 by Wallace
Write a  C++program to do the following ADT

stack

que

pop

linked list

1 Answer

0 votes
answered Mar 25, 2022 by Omprakash Kumar (250 points)
#include <bits/stdc++.h>

using namespace std;

#define MAX 1000

class Stack {

    int top;

public:

    int a[MAX];

    Stack() { top = -1; }

    bool push(int x);

    int pop();

    int peek();

    bool isEmpty();

};

bool Stack::push(int x)

{

    if (top >= (MAX - 1)) {

        cout << "Stack Overflow";

        return false;

    }

    else {

        a[++top] = x;

        cout << x << " pushed into stack\n";

        return true;

    }

}

int Stack::pop()

{

    if (top < 0) {

        cout << "Stack Underflow";

        return 0;

    }

    else {

        int x = a[top--];

        return x;

    }

}

int Stack::peek()

{

    if (top < 0) {

        cout << "Stack is Empty";

        return 0;

    }

    else {

        int x = a[top];

        return x;

    }

}

bool Stack::isEmpty()

{

    return (top < 0);

}

int main()

{

    class Stack s;

    s.push(10);

    s.push(20);

    s.push(30);

    cout << s.pop() << " Popped from stack\n";

 

    cout<<"Elements present in stack : ";

    while(!s.isEmpty())

    {

        // print top element in stack

        cout<<s.peek()<<" ";

        

        s.pop();

    }

    return 0;

}
commented Mar 26, 2022 by Peter Minarik (86,040 points)
edited Mar 26, 2022 by Peter Minarik
Your code looks like it works just fine! :)

Here are some improvement ideas:

1. Your stack is limited to a predetermined size. It would be nice if either this size is configurable (e.g. passed to the constructor) or the size dynamically changes based on how many elements you put in it.
2. You implemented a concrete stack for integers. The original description talked about abstract data type, so you should implement a generic (template) class instead.
Welcome to OnlineGDB Q&A, where you can ask questions related to programming and OnlineGDB IDE and and receive answers from other members of the community.
...