Computer ScienceAlgorithms & Data StructuresAdvanced

Stack (data structure)

Also known as:LIFO QueuePushdown StackPushdown Automaton (storage component)

A stack is an abstract data type that follows the Last-In-First-Out (LIFO) principle, where elements are added (pushed) and removed (popped) only from one end called the top. Stacks support three primary operations: push (add element to top), pop (remove and return top element), and peek/top (inspect top element without removal), all in O(1) time. They are fundamental to function call management (call stack), expression evaluation (operator precedence, postfix notation), depth-first search, backtracking algorithms, and undo mechanisms in text editors.

Stack Operations, Complexities, and Implementation Comparison

OperationTime ComplexityArray ImplementationLinked List ImplementationNotes
push(x)O(1) amortisedIncrement top, assignCreate node, set headArray may resize
pop()O(1)Return top, decrementReturn head, update headRaises exception if empty
peek() / top()O(1)Return A[top]Return head.dataDoes not remove element
isEmpty()O(1)Check top == -1Check head == nullEssential guard before pop
size()O(1)Return top+1Maintain counterOptional, O(n) if uncached
search(x)O(n)Linear scanLinear traversalNot a primary stack operation

Interactive Tools

VisuAlgo — Stack Visualiser

Open Tool

Brilliant — Stacks

Open Tool

Khan Academy — Stacks and Queues

Open Tool
Diagram of a stack data structure showing push and pop operations at the top

Wikimedia Commons, CC BY-SA

Related Terms

The term "stack" in computing derives from the physical metaphor of a stack of plates or trays where only the top item is accessible. It was formalised in computing by Friedrich Bauer and Klaus Samelson who patented a "Kellerprinzip" (cellar principle) stack-based processor architecture in Germany in 1957. The English term "stack" was used by Charles Leonard Hamblin in 1957 for his stack-based Reverse Polish Notation calculator design.

data-structureslifostackrecursionexpression-evaluationcall-stack