Skip to content
  • Open the math solver
  • Ask the AI tutor
  • Find an AP course
  • Create a quiz
  • Open the calculator
  • Graphing Calculator
  • Browse all calculators
  • Read math guides
↑ ↓Enter to open · Esc to close
Solve a problem
Data StructuresData StructuresCollege

Stacks and Queues

LIFO and FIFO structures.

A stack is a last-in, first-out (LIFO) collection: you push items onto the top and pop them off the top, like a pile of plates. A queue is first-in, first-out (FIFO): you enqueue at the back and dequeue from the front, like a checkout line. Both restrict access on purpose, which makes them simple, fast and hard to misuse.

Stacks power function calls (the call stack), undo features, bracket matching and depth-first search. Queues schedule print jobs, buffer network data and drive breadth-first search. Both support their main operations in constant time.

Key ideas

  • Stack: push, pop, peek at the top, all O(1)O(1).
  • Queue: enqueue at the back, dequeue at the front, all O(1)O(1) with a linked list or circular buffer.
  • Popping an empty stack is an underflow error; check first.
  • A deque allows adding and removing at both ends.

Worked example

Starting empty, a stack does push 3, push 8, pop, push 5, push 1, pop. What is on top, and what would a queue give for the same operations?

  1. Stack: [3] → [3, 8] → pop 8 → [3, 5] → [3, 5, 1] → pop 1. Top is 5.
  2. Queue: [3] → [3, 8] → dequeue 3 → [8, 5] → [8, 5, 1] → dequeue 8. Front is 5.
  3. Same final front value here by coincidence; the removed items differ (8 and 1 versus 3 and 8).

Answer: Stack top 55; queue front 55

Common mistakes

  • Mixing up LIFO and FIFO.
  • Implementing a queue with an array that shifts on every dequeue, making it O(n)O(n).
  • Forgetting to check for an empty structure before removing.

Practice questions

Try each one, then open the answer. Numerical answers on this page are verified by an automated calculation check.

  1. 1.Push 1, 2, 3 onto a stack, then pop twice. What remains on top?

    Show answer

    11

  2. 2.Enqueue 1, 2, 3, then dequeue once. Which is at the front?

    Show answer

    22

  3. 3.Which structure checks matching brackets: stack or queue?

    Show answer

    A stack

More in Data Structures