top = -1
top = 0
top = \(MAX\_SIZE - 1\)
TOP
TOP (-1)
MAX_SIZE =
MAX_SIZE = 5
stack = [None] * MAX_SIZE
top = -1 # -1 indicates the stack is currently empty
def push(item):
global top
# 1. Check for Overflow (Is the array full?)
if top >= MAX_SIZE - 1:
print("Error: Stack Overflow!")
return False
# 2. Increment top pointer FIRST
# We must move the pointer to the next empty slot before inserting
top += 1
# 3. Insert item at the new top position
stack[top] = item
return True
def pop():
global top
# 1. Check for Underflow (Is the array empty?)
if top == -1:
print("Error: Stack Underflow!")
return None
# 2. Retrieve the item currently at the top
item = stack[top]
# 3. Decrement top pointer AFTER retrieval
# The item remains in memory, but is logically removed from our stack
top -= 1
return item
#include <iostream>
using namespace std;
const int MAX_SIZE = 5;
int stack[MAX_SIZE];
int top = -1; // -1 indicates the stack is currently empty
bool push(int item) {
// 1. Check for Overflow (Is the array full?)
if (top >= MAX_SIZE - 1) {
cout << "Error: Stack Overflow!" << endl;
return false;
}
// 2. Increment top pointer FIRST
// We must move the pointer to the next empty slot before inserting
top++;
// 3. Insert item at the new top position
stack[top] = item;
return true;
}
int pop() {
// 1. Check for Underflow (Is the array empty?)
if (top == -1) {
cout << "Error: Stack Underflow!" << endl;
return -1; // Assuming -1 indicates error for this example
}
// 2. Retrieve the item currently at the top
int item = stack[top];
// 3. Decrement top pointer AFTER retrieval
// The item remains in memory, but is logically removed from our stack
top--;
return item;
}