Stacks and queues
Stacks and queues both store sequences of items, but they remove them in different orders.
Stack: LIFO
Section titled “Stack: LIFO”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.
var stack = new Stack<int>();stack.Push(10);stack.Push(20);int value = stack.Pop(); // 20Queue: FIFO
Section titled “Queue: FIFO”First in, first out. The oldest enqueued item is the first dequeued. Queues are useful for work scheduling and breadth-first search.
var queue = new Queue<int>();queue.Enqueue(10);queue.Enqueue(20);int value = queue.Dequeue(); // 10Comparing operations
Section titled “Comparing operations”| 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.