Data Structures10 min read

Stacks and Queues: LIFO and FIFO Data Structures

Master stacks and queues - two essential data structures. Learn LIFO (Last In First Out) and FIFO (First In First Out) principles, when to use each, and real-world applications. Used in countless algorithms.

Robert Kim
December 18, 2025
0.0k0

Stacks and queues are simple but powerful data structures. They restrict how you can access data, which makes them perfect for specific problems. Understanding them opens up many algorithm solutions.

What is a Stack?

A stack follows LIFO (Last In First Out) - like a stack of plates. You add to the top and remove from the top. Think of the undo feature in editors - that's a stack.

What is a Queue?

A queue follows FIFO (First In First Out) - like a line at a store. You add to the back and remove from the front. Think of print jobs or task scheduling - that's a queue.

Common Operations

Both have simple operations: push/pop for stacks, enqueue/dequeue for queues. All operations are O(1) when implemented correctly. I'll show you how.

Real-World Applications

Stacks are used for expression evaluation, undo/redo, function calls, and backtracking. Queues are used for task scheduling, BFS algorithms, and buffering. I'll show you practical examples.

Implementation

I'll walk you through implementing both using arrays and linked lists. You'll see how simple they are and why they're so useful.

#Data Structures#Stacks#Queues#LIFO#FIFO

Common Questions & Answers

Q1

What is a stack and how does it work?

A

A stack is a LIFO (Last In First Out) data structure. Elements are added (push) and removed (pop) from the same end (top). Operations are O(1). Used for expression evaluation, undo/redo, function call stack, and backtracking algorithms.

javascript
class Stack {
  constructor() {
    this.items = [];
  }
  
  push(element) {
    this.items.push(element);  // O(1)
  }
  
  pop() {
    return this.items.pop();   // O(1)
  }
  
  peek() {
    return this.items[this.items.length - 1];
  }
  
  isEmpty() {
    return this.items.length === 0;
  }
}

// Usage
const stack = new Stack();
stack.push(1);
stack.push(2);
stack.push(3);
stack.pop();  // Returns 3 (last in, first out)
Q2

What is a queue and how does it work?

A

A queue is a FIFO (First In First Out) data structure. Elements are added (enqueue) at the back and removed (dequeue) from the front. Operations are O(1). Used for task scheduling, BFS algorithms, print queues, and message buffering.

javascript
class Queue {
  constructor() {
    this.items = [];
  }
  
  enqueue(element) {
    this.items.push(element);  // Add to back
  }
  
  dequeue() {
    return this.items.shift();  // Remove from front
  }
  
  front() {
    return this.items[0];
  }
  
  isEmpty() {
    return this.items.length === 0;
  }
}

// Usage
const queue = new Queue();
queue.enqueue('Task 1');
queue.enqueue('Task 2');
queue.enqueue('Task 3');
queue.dequeue();  // Returns 'Task 1' (first in, first out)