Skip to content

Stacks and queues

Stacks and queues both store sequences of items, but they remove them in different orders.

Last in, first out. The most recently pushed item is the first one popped. A stack is useful for undo operations and depth-first search.

C# | Stack
var stack = new Stack<int>();
stack.Push(10);
stack.Push(20);
int value = stack.Pop(); // 20

First in, first out. The oldest enqueued item is the first dequeued. Queues are useful for work scheduling and breadth-first search.

C# | Queue
var queue = new Queue<int>();
queue.Enqueue(10);
queue.Enqueue(20);
int value = queue.Dequeue(); // 10
Operation Stack Queue
Add Push Enqueue
Remove Pop Dequeue
Typical time complexity O(1) O(1)

Typical complexities assume an appropriate implementation and exclude occasional resizing costs.