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;
}