Java ProgramsCollectionsLinkedList Queue

LinkedList Queue in Java

beginner·  Collections  ·  Queue & Stack

Problem

LinkedList implements the Queue interface, so it can be used for strict first-in-first-out ordering just by declaring the reference as type Queue instead of LinkedList.

Given a sequence of tickets, process them in the exact order they arrived using a Queue-typed LinkedList.

Input
offer(Ticket-1), offer(Ticket-2), offer(Ticket-3)
Output
Serving: Ticket-1 Serving: Ticket-2 Serving: Ticket-3

Java Program

Java
import java.util.LinkedList; import java.util.Queue; public class LinkedListQueue { public static void main(String[] args) { Queue<String> tickets = new LinkedList<>(); tickets.offer("Ticket-1"); tickets.offer("Ticket-2"); tickets.offer("Ticket-3"); while (!tickets.isEmpty()) { System.out.println("Serving: " + tickets.poll()); // removes from the front } } }

Output

Serving: Ticket-1 Serving: Ticket-2 Serving: Ticket-3

Core Logic

Declaring the variable as Queue<String>, backed by a LinkedList, restricts the visible operations to the queue's enqueue/dequeue vocabulary rather than LinkedList's full list API.

How It Works
  1. 1Queue<String> tickets = new LinkedList<>(); creates a LinkedList but exposes it only through the Queue interface's methods.
  2. 2offer(...) adds each ticket to the back of the queue, in arrival order.
  3. 3poll() removes and returns the ticket at the front of the queue — always whichever one has been waiting the longest.
  4. 4The while (!tickets.isEmpty()) loop keeps polling until every ticket has been served, in the same order they were offered.
Offering Ticket-1, Ticket-2, and Ticket-3 in that order, and then polling repeatedly, serves them back in the exact same order.
💡

Key Point: Declaring the variable's type as Queue rather than LinkedList is a deliberate choice — it makes clear this code only relies on queue behavior, and the underlying implementation could be swapped for another Queue without changing any of this logic.

Complexity
Time Complexity: O(1)Space Complexity: O(1)

Why: Both offer() and poll() operate directly on LinkedList's tail and head references, with no dependency on how many elements the queue currently holds.

Key Concepts

Queue interfaceoffer()poll()

Related Programs