data-structures

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:

  1. : Adds element to the top of the stack.
  2. : Removes and returns the element at the top.
  3. : 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

OperationTime 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.