Skip to content

Queues

This content is for DSA. Switch to the latest version for up-to-date documentation.

Image

A queue is a linear data structure that follows the First-In-First-Out (FIFO) principle, meaning the first element added is the first one to be removed. Think of it like a line of people waiting - the person who arrives first gets served first.

  • FIFO (First In, First Out) ordering: The first element added is the first one to be removed.
  • Elements added at rear (enqueue): New elements are always added to the back of the queue.
  • Elements removed from front (dequeue): Elements are always removed from the front of the queue.
  • Can be implemented using arrays or linked lists: Flexible implementation options depending on needs.
  • Print job management: Handling print requests in the order they were submitted.
  • Call center systems: Managing incoming calls in the order they arrive.
  • Enqueue: Add element to the rear (back) of the queue.
  • Dequeue: Remove and return element from the front of the queue.
  • Fair processing (first come, first served): Ensures elements are processed in the order they arrive.
  • Efficient for sequential processing: All basic operations have O(1) time complexity.
  • Easy to implement: Simple structure with clear insertion and deletion points.
  • Limited access pattern: Can only access the front element directly.
import java.util.Queue;
import java.util.LinkedList;
Queue<String> students = new LinkedList<>();
// Enqueue elements
students.offer("Jalen");
students.offer("Nawiesh");
students.offer("Rafael");
// Get queue size
System.out.println(students.size()); // Prints 3
// Accessing the front element
System.out.println(students.peek()); // Prints "Jalen"
// Dequeue elements
students.poll(); // Removes "Jalen", queue: [Nawiesh, Rafael]
students.poll(); // Removes "Nawiesh", queue: [Rafael]
System.out.println(students);
Built with passion by Ngineer Lab