DEV Community

Mujahida Joynab
Mujahida Joynab

Posted on

Stack Implementation using Array

While pop or insert we have to check if the stack is empty

#include <bits/stdc++.h>
using namespace std;
class myStack
{
public:
    vector<int> v;
    void push(int val)
    {
        v.push_back(val); //- TC - O(1)
    }

    void pop()
    {
        v.pop_back(); //- TC - O(1)
    }

    int top()
    {
        if (!v.empty())
        {
            return v.back(); // TC - O(1)
        }
    }
    int size()
    {
        return v.size(); //- TC - O(1)
    }

    bool empty()
    {
        return v.empty(); // TC-O(1)
    }
};

int main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    cout.tie(NULL);

    myStack st;
    st.push(10);
    st.push(20);
    st.push(30);
    cout << st.top() << endl;
    st.pop();
    cout << st.top() << endl;

    st.pop();

    cout << st.top() << endl;

    st.pop();

    if (!st.empty())
        cout << st.top() << endl;



    return 0;
}
Enter fullscreen mode Exit fullscreen mode

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

Top comments (0)

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay