#include <iostream>
#include <string>
using namespace std;
// TODO: Define Class Template 'StaticStack'
// Template Parameters: typename T, int Capacity
template <typename T, int Capacity>
class StaticStack {
private:
T buffer[Capacity];
int top_index; //points to current top
public:
StaticStack() : top_index(-1) {}
// TODO: Implement push(val) - Check for overflow
void push(T val){
if(top_index < Capacity -1){
buffer[++top_index] = val;
}
else{
cout << "Stack Overflow" << endl;
}
}
// TODO: Implement pop() - Check for underflow
void pop(){
if(top_index >= 0){
top_index--;
}
else{
cout << "Stack Underflow" << endl;
}
}
// TODO: Implement peek() - Return current top
T peek(){
return buffer[top_index];
}
// TODO: Implement isEmpty()
bool isEmpty(){
return top_index >= 0 ? false : true;
}
};
int main() {
// Instantiate a stack of int with capacity 3
StaticStack<int, 3> stack;
int N;
if (!(std::cin >> N)) return 0;
for (int i = 0; i < N; ++i) {
std::string cmd;
std::cin >> cmd;
if (cmd == "PUSH") {
int val;
std::cin >> val;
stack.push(val);
} else if (cmd == "POP") {
stack.pop();
} else if (cmd == "PEEK") {
// Simple safety check for peek printing in main
if (!stack.isEmpty()) {
std::cout << "Top: " << stack.peek() << std::endl;
} else {
std::cout << "Stack Empty" << std::endl;
}
} else if (cmd == "EMPTY") {
std::cout << "Empty: " << (stack.isEmpty() ? "Yes" : "No") << std::endl;
}
}
return 0;
}
Input
6 PUSH 10 PUSH 20 PUSH 30 PUSH 40 PEEK POP
Expected Output
Stack Overflow Top: 30