#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];
int top_index; // Points to the index of the next free slot OR current top
public:
StaticStack() : top_index(0) {}
// TODO: Implement push(val) - Check for overflow
void push(int val){
if(top_index==Capacity){
std::cout << "Stack Overflow\n";
}
else{
buffer[top_index] = val;
top_index++;
}
}
// TODO: Implement pop() - Check for underflow
int pop(){
if(top_index>=1){
int val = buffer[top_index-1];
top_index--;
return val;
}
else{
std::cout << "Stack Underflow\n";
return 0;
}
}
// TODO: Implement peek() - Return current top
int peek() const{
if(top_index>=1){
return buffer[top_index-1];
}
else{
return 0;
}
}
// TODO: Implement isEmpty()
bool isEmpty() const{
if (top_index == 0){
return true;
}
else{
return false;
}
}
};
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