DEV Community

Mujahida Joynab
Mujahida Joynab

Posted on

Stack Input and Output

If we want to access a value and that is not at top in stack we have to keep deleting element of top while that element is not coming .

#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;
    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)