DEV Community

Mujahida Joynab
Mujahida Joynab

Posted on

Stack implementation using list

#include <bits/stdc++.h>
using namespace std;
class myStack
{
public:
    list<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;
    int n;
    cin >> n;
    for (int i = 0; i < n; i++)
    {
        int x;
        cin >> x;
        st.push(x);
    }
    while (!st.empty())
    {
        cout << st.top() << endl;
        st.pop();
    }
    return 0;
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

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

Okay