Push and Pop
Push and pop are the two fundamental operations that define how data enters and leaves a stack. Every other stack operation builds on these two.
The Push Operation
Push is the operation that adds a new element to the top of the stack. It is the only way to insert data. A stack does not allow insertion at any other position.
Step-by-Step Process
top to top + 1. In a linked list this means creating a new node.The Pop Operation
Pop removes the element at the top of the stack and returns it. This is the only way to remove data from a stack. You cannot remove elements from the middle or bottom.
Step-by-Step Process
top in a temporary variable so you can return it.top - 1. In a linked list, free the old top node and set head to the next node.What Happens During a Stack Overflow
Stack overflow occurs when you try to push an element onto a stack that has no remaining capacity. This only happens with fixed-size array stacks where the array has a predetermined maximum length.
In the call stack, stack overflow happens when recursion goes too deep. Each recursive call adds a frame, and if the call stack exceeds its limit (typically a few megabytes), the program crashes with a stack overflow error.
What Happens During a Stack Underflow
Stack underflow occurs when you try to pop or peek from an empty stack. There is no top element to return.
A common defensive pattern is to wrap pop in a conditional:
if (!isEmpty()) {
value = pop();
// use value
}
Push and Pop in Memory
Understanding what happens in memory helps you choose the right implementation and debug issues.
Array Stack Memory
An array stack stores elements in contiguous memory. When you push, the new element goes into the next available slot. The top variable (an integer index) points to the highest occupied position. The array itself does not move; only the index changes.
This makes array stacks very fast because accessing contiguous memory is cache-friendly. The CPU can load adjacent elements into the cache line in a single memory access.
Linked List Stack Memory
A linked list stack stores each element in a separate node allocated on the heap. Each node contains the data and a pointer to the next node. Pushing allocates a new node and updates the head pointer. Popping frees the head node and moves the pointer forward.
Each node may live at a different address in memory, so the CPU cannot predict the next access pattern. This makes linked list stacks slightly slower in practice due to cache misses, even though both have O(1) time complexity.
Code Examples in 5 Languages
C
#define MAX 1000
int stack[MAX], top = -1;
void push(int x) {
if (top == MAX - 1) {
printf("Stack overflow\n");
return;
}
stack[++top] = x;
}
int pop() {
if (top == -1) {
printf("Stack underflow\n");
return -1;
}
return stack[top--];
}
C++
#include <stack>
#include <iostream>
std::stack<int> s;
void pushExample() {
s.push(10);
s.push(20);
s.push(30);
}
int popExample() {
if (s.empty()) {
std::cout << "Stack underflow\n";
return -1;
}
int val = s.top();
s.pop();
return val;
}
Java
import java.util.Stack;
Stack<Integer> stack = new Stack<>();
// Push
stack.push(10);
stack.push(20);
stack.push(30);
// Pop
if (!stack.isEmpty()) {
int top = stack.pop();
System.out.println("Popped: " + top);
}
Python
stack = []
# Push
stack.append(10)
stack.append(20)
stack.append(30)
# Pop
if stack:
top = stack.pop()
print(f"Popped: {top}")
# Peek
if stack:
print(f"Top: {stack[-1]}")
JavaScript
const stack = [];
// Push
stack.push(10);
stack.push(20);
stack.push(30);
// Pop
if (stack.length > 0) {
const top = stack.pop();
console.log("Popped:", top);
}
// Peek
if (stack.length > 0) {
console.log("Top:", stack[stack.length - 1]);
}
Common Mistakes with Push and Pop
top < MAX - 1 before pushing. Forgetting this check causes a buffer overflow which is undefined behavior in C and C++.
Frequently Asked Questions
Can push and pop be done in any order?
No. Push always adds to the top and pop always removes from the top. You cannot push to the middle or bottom of a stack. If you need random access, use an array or list instead.
What is the difference between stack overflow and stack underflow?
Stack overflow happens when you push onto a full fixed-size stack. Stack underflow happens when you pop from an empty stack. Both are errors that must be handled.
Do all programming languages handle push and pop the same way?
The concept is the same across all languages, but the syntax differs. Python uses list.append() and list.pop(), Java uses Deque.push() and Deque.pop(), C uses struct pointers, and so on.
What happens in memory when you push an element?
In an array stack, the element is written to the next available index and the top pointer increments. In a linked list stack, a new node is allocated on the heap and its next pointer is set to the current top node.
Is it possible to push multiple elements at once?
Conceptually no - each push is an individual O(1) operation. You can push elements in a loop to add many at once, but each push is still a separate operation under the hood.