#include <iostream>
#include <string>
// TODO: Define Class Template 'StaticStack'
// Template Parameters: typename T, int Capacity
template <typename T, int Capacity>
class StaticStack {
private:
T buffer[Capacity]; // 0 , 1 , 2
int top_index; // Points to the index of the next free slot OR current top
public:
StaticStack() : top_index(-1) {}
// TODO: Implement push(val) - Check for overflow
void push(T val){
if ( (top_index + 1) >= Capacity)
std::cout << "Stack Overflow\n";
else
{
buffer[top_index + 1] = val;
top_index++;
}
}
// TODO: Implement pop() - Check for underflow
void pop()
{
if (top_index <= -1)
std::cout << "Stack Underflow\n";
else
--top_index;
}
// TODO: Implement peek() - Return current top
T peek()
{
if ( top_index <= -1) return T(0);
return buffer[top_index];
}
// TODO: Implement isEmpty()
bool isEmpty()
{
return top_index <= -1;
}
};
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