stack cpp code example
Example 1: stack c++
stack<int> stk;
stk.push(5);
int ans = stk.top(5); // ans =5
stk.pop();//removes 5
Example 2: stack c++
/* Stack is a data structure that provides two O(1) time operations:
adding an element to the top and removing an element from the top.
It is only possible to access the top element of a stack. */
stack<int> s;
s.push(3);
s.push(2);
s.push(5);
cout << s.top(); // 5
s.pop();
cout << s.top(); // 2
Example 3: cpp stack
// Fast DIY Stack
template<class S, const int N> class Stack {
private:
S arr[N];
int top_i;
public:
Stack() : arr(), top_i(-1) {}
void push (S n) {
arr[++top_i] = n;
}
void pop() {
top_i--;
}
S top() {
return arr[top_i];
}
S bottom() {
return arr[0];
}
int size() {
return top_i+1;
}
};
Example 4: stack c++
stack<int> stk;
stk.push(5);
int ans = stk.top(5); // ans =5
stk.pop();//removes 5