LinkedList Queue in Java
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.
Java Program
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
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.
- 1
Queue<String> tickets = new LinkedList<>();creates aLinkedListbut exposes it only through theQueueinterface's methods. - 2
offer(...)adds each ticket to the back of the queue, in arrival order. - 3
poll()removes and returns the ticket at the front of the queue — always whichever one has been waiting the longest. - 4The
while (!tickets.isEmpty())loop keeps polling until every ticket has been served, in the same order they were offered.
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.
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.