Implementation of a Stack using fixed-size arrays to demonstrate the underlying logic of Top pointer management.
#include <iostream> using namespace std; #define MAX 100 class Stack { int top; public: int arr[MAX]; Stack() { top = -1; } // Initialize top void push(int x) { if (top >= MAX - 1) { cout << "Overflow"; return; } arr[++top] = x; // Increment then insert } int pop() { if (top < 0) { cout << "Underflow"; return -1; } return arr[top--]; // Return then decrement } int peek() { return (top < 0) ? -1 : arr[top]; } };
class Stack { static final int MAX = 1000; int top; int a[] = new int[MAX]; Stack() { top = -1; } boolean push(int x) { if (top >= (MAX - 1)) { System.out.println("Stack Overflow"); return false; } a[++top] = x; return true; } int pop() { if (top < 0) { System.out.println("Stack Underflow"); return 0; } return a[top--]; } }
class Stack: def __init__(self, size): self.size = size self.stack = [None] * size self.top = -1 def push(self, item): if self.top == self.size - 1: print("Stack Overflow") else: self.top += 1 self.stack[self.top] = item def pop(self): if self.top == -1: print("Stack Underflow") return None val = self.stack[self.top] self.top -= 1 return val