#include <iostream>
using namespace std;
class Stack {
private:
int* arr; // Pointer to the array
int top; // Index of the top element
int capacity; // Maximum size of stack
public:
// Constructor
Stack(int size) {
capacity = size;
arr = new int[capacity];
top = -1; // Stack is empty initially
}
// Destructor
~Stack() {
delete[] arr;
}
// Check if stack is empty
bool isEmpty() {
return top == -1;
}
// Check if stack is full
bool isFull() {
return top == capacity - 1;
}
// Push an element to the stack
void push(int val) {
if (isFull()) {
cout << "Stack overflow! Cannot push " << val << "\n";
return;
}
top++;
arr[top] = val;
cout << val << " pushed to stack\n";
}
// Pop an element from the stack
void pop() {
if (isEmpty()) {
cout << "Stack underflow! Cannot pop\n";
return;
}
int popped = arr[top];
top--;
cout << popped << " popped from stack\n";
}
// Peek / top element
void peek() {
if (isEmpty()) {
cout << "Stack is empty, nothing to peek\n";
return;
}
cout << "Top element is: " << arr[top] << "\n";
}
// Print stack elements
void print() {
if (isEmpty()) {
cout << "Stack is empty\n";
return;
}
cout << "Stack elements (top to bottom): ";
for (int i = top; i >= 0; i--) {
cout << arr[i] << " ";
}
cout << "\n";
}
};
// Usage Example
int main() {
Stack s(5); // Stack of size 5
[Link](10);
[Link](20);
[Link](30);
[Link](); // 30 20 10
[Link](); // Top element: 30
[Link]();
[Link](); // 20 10
[Link]();
[Link]();
[Link](); // Underflow
return 0;
}