STACKLIFO
size: 0
TOP ↓
stack empty
BOTTOM
push
O(1)
pop
O(1)
peek top
O(1)
order
LIFO
Stack — LIFO (Last In, First Out). Push adds to top. Pop removes from top.
stack
1 / 14
SPD0.5×
click to pause · hover for controls · fullscreen for more

Stack & Queue

LIFO vs FIFO — two structures, two totally different orders

Visual by thisgirltech

BeginnerData Structure

A Stack and a Queue are both linear data structures that store a sequence of elements — but they differ in one critical way: the order in which elements leave.

A Stack is LIFO (Last In, First Out) — the most recently added element is always removed first, like a stack of plates. A Queue is FIFO (First In, First Out) — the oldest element is always removed first, like people waiting in line.

Stack — LIFO

push() adds to the top. pop() removes from the top. The last item pushed is always the first item popped.

Queue — FIFO

enqueue() adds to the back. dequeue() removes from the front. The first item enqueued is the first item dequeued.

Both O(1)

Push, pop, enqueue, and dequeue are all O(1) operations — constant time regardless of size.

TIP

Stacks are used whenever you need to reverse something or track nested structure — think recursion, undo, and bracket matching. Queues are used whenever order of arrival matters — think BFS, task scheduling, and print spoolers.

COLOUR LEGEND

Stack
Queue
Push / Enqueue
Pop / Dequeue
Active element