Hide sidebar

Introduction to Stacks

A Stack is a linear data structure that follows the Last-In, First-Out (LIFO) principle. This means that the last element added to the stack will be the first one to be removed.

Stacks are commonly used in programming for tasks such as managing function calls (the call stack), parsing expressions, and implementing undo/redo functionality.

Interactive Stack Visualization

The visualization below demonstrates the basic operations of a stack. You can see how elements are pushed and popped from the top of the stack.

Stack Visualization (LIFO)

Current Step
1 of 11
Last Operation
Ready to start
Stack Size
3
Stack operations will appear here...
STACK BASE
10
20
30
← TOP
↑ Stack grows upward (LIFO: Last In, First Out)
Auto-resets when full (6 max) or empty to keep cycling

Array View

[10,20,30]← index 2 (top)
+
PUSH
Add to top
-
POP
Remove from top
👁
PEEK
View top (no remove)
Stack (LIFO): Elements are added and removed from the top only. Like a stack of plates - you can only take the top plate! All operations are O(1) time complexity. This demo auto-resets to keep cycling through operations.

Stack Data Structure

A Stack is a linear data structure that follows the Last-In, First-Out (LIFO) principle. It's like a stack of plates: you can only add a new plate to the top, and you can only remove the top plate.

Key Operations

  • Push: Adds an element to the top of the stack.
  • Pop: Removes the top element from the stack.
  • Peek/Top: Returns the top element without removing it.
  • isEmpty: Checks if the stack is empty.
Stack Implementation

# Using a list as a stack
stack = []

# Push
stack.append(1)
stack.append(2)
stack.append(3)

# Pop
top_element = stack.pop()  # 3

# Peek
top_element = stack[-1]  # 2

# isEmpty
if not stack:
    print("Stack is empty")