Implement Queue using Linked List

easy

Implement a queue (first-in, first-out) backed by a singly linked list with a tail pointer, supporting:

  • push(x) — add x to the back of the queue.
  • pop() — remove and return the front element; return -1 if the queue is empty.

Both operations must be O(1).

Hints

A singly linked list is O(1) at the head — how do you make the back O(1) too?
Keep a tail pointer so push appends without traversing.
Pop from the head; reset the tail to null when the queue empties.

Common doubts

Enqueue happens at the back. Without a tail pointer you'd traverse the whole list to find the last node (O(n)); the tail pointer makes it O(1).
The tail would still point at the removed node, so the next push links after a node that's no longer in the queue, corrupting it.

Interview follow-ups

Return head's value without advancing head — O(1).
A queue only needs O(1) at both ends, which a singly linked list with a tail pointer already provides; the extra prev pointers aren't needed.

Fun facts

  • This head/tail singly linked list is the standard implementation of a queue in most standard libraries' linked structures.
  • Lock-free concurrent queues (Michael–Scott) are built on exactly this head/tail node design with atomic pointer swaps.

Asked at

AmazonMicrosoft
Frequently Sometimes Occasionally
Example 1
Input: push(5), push(10), pop(), pop(), pop()
Output: 5, 10, -1
FIFO: 5 dequeues first, then 10, then -1.
Example 2
Input: push(7), pop()
Output: 7
Push 7, pop returns 7.
Constraints

- 1 <= number of operations <= 100 - 1 <= x <= 10^5 - pop() returns -1 if the queue is empty.

Solve this problem →