pvdocs /Data Structure/Stack

Stack

A stack follows LIFO — Last In, First Out. The last element added is the first one to be removed, like a stack of plates.


Two Core Operations

Both are always O(1) — you only ever touch the top of the stack.

Push 1:  [1]
Push 2:  [1] → [2]   ← top is 2

Pop:     [1]          ← returns 2, top is now 1
Pop:     []           ← returns 1, stack is empty

Visual

Elements are chained like a linked list, where each node points to the previous one:

bottom          top
  [1]    ←    [2]
              ↑
           always here (push/pop)

Adding node 2 makes it point back to node 1. Popping removes node 2 and the top becomes node 1 again.


In Python

Python lists work as a stack out of the box:

stack = []

stack.append(1)   # push → [1]
stack.append(2)   # push → [1, 2]
stack.append(3)   # push → [1, 2, 3]

stack.pop()       # → 3  (last in, first out)
stack.pop()       # → 2

For thread-safe usage:

from queue import LifoQueue

stack = LifoQueue()
stack.put(1)
stack.put(2)
stack.get()  # → 2

Real-World Uses


Big O Summary

Operation Time
Push (add to top) O(1)
Pop (remove from top) O(1)
Peek (read top without removing) O(1)
Search O(n)

Stack vs Queue

Order Add Remove
Stack LIFO top top
Queue FIFO tail head

Key Takeaways