Introduction to Stack

This lesson defines the stack as an abstract data type, explains LIFO (last-in, first-out), introduces push, pop, and peek, and contrasts a stack with a queue. Later pages cover implementations in C, expressions, and applications.

On this page
  • What is a stack? — LIFO mental model
  • Core operations: push, pop, peek (or top)
  • Overflow, underflow, and empty stack
  • Stack vs queue — quick comparison
  • Where stacks appear in practice — next lessons

1) What is a stack?

A stack is a linear collection where elements are added and removed from the same end, called the top. The last item you push is the first one you pop—so a stack follows last-in, first-out (LIFO).

Think of a stack of plates: you only add or remove from the top. You do not pull from the middle without disturbing the rest. That restriction is what makes the structure simple to reason about and efficient for many algorithms.

Schematic: growth at the top

After pushing A, then B, then C (top is right):

        ┌───┐  ← top (pop removes C first)
        │ C │
        ├───┤
        │ B │
        ├───┤
        │ A │
        └───┘
        bottom

2) Core operations

  • Push — Insert an element at the top. On a full array-based stack, pushing can cause overflow if capacity is fixed.
  • Pop — Remove and return the top element. Popping an empty stack is underflow (an error state you must avoid in C).
  • Peek / Top — Read the top value without removing it. Useful when you need to inspect the next action (e.g. matching brackets) before deciding to pop.

Exact names vary (push, pop, peek, top, isEmpty, isFull); the ideas stay the same.

3) Stack vs queue

Both are linear ADTs with restricted access, but the removal order differs:

ADT Order Insert Remove
Stack LIFO At top From top
Queue FIFO (first-in, first-out) At rear From front

4) Where stacks show up

Stacks model anything that must be reversed or nested in time order: function call stacks, undo buffers, parenthesis matching, depth-first exploration, converting or evaluating expressions, and browser back history (often paired with another structure for “forward”). This tutorial’s later pages walk through implementations and classic problems in C.

Key takeaway

A stack is a LIFO line: all the action happens at the top. Master push, pop, and peek, guard empty and full conditions in C, and the same pattern will repeat in parsing, recursion, and interview problems.

Next up: Stack applications · Stack operations · Stack using array