Definition
Stack
A stack is a linear data structure that follows the Last In, First Out (LIFO) principle. In a stack, all insertions and deletions are restricted to a single end, called the top.
It provides three primary operations:
- : Adds element to the top of the stack.
- : Removes and returns the element at the top.
- : Returns the element at the top without removing it.
Visual Representation
A stack is often compared to a stack of physical objects, where only the top item is accessible:
Implementation
Array-based
Using a dynamic array or a fixed-size array with a top index:
- : (amortised if resizing is needed).
- :.
Linked List
Using a singly linked list:
- New elements are pushed to the head.
- Popping occurs from the head.
- Both operations are strictly .
Complexity
| Operation | Time Complexity |
|---|---|
Use Cases
- Function Call Stack: Managing activation records in programming languages.
- Expression Evaluation: Parsing and evaluating postfix notation (Reverse Polish Notation).
- Undo/Redo: Maintaining state history in applications.
- Recursion: Emulated using an explicit stack.