Skip to content

Implementing a Queue - Linked List

Similar to how we implemented a stack using linked lists we will now implement a queue using the same technique. The difference being we will need to maintain two pointers due to the enqueue and dequeue operations needing to maintain pointers for the “front” and “end” of the list.

Assume the following inner class structure

private class Node{
String item;
Node next;
}
  1. Save item to return
String item = first.item;
  1. Delete first node
first = first.next;
  1. Return saved item
return item;
  1. Save pointer to current last node
Node oldLast = last;
  1. Create a new node to be the new last
last = new Node();
  1. Set the item and next for the new last node
last.item = item;
last.next = null;
  1. Handle empty queue special case:
if (isEmpty())
{
first = last;
}
  1. Link the previous last node to the new last node (if not empty):
else { oldLast.next = last; }
public class LinkedQueueOfStrings
{
private Node first , last;
private class Node
{
String item;
Node next;
}
public boolean isEmpty()
{ return first == null; }
public void enqueue(String item)
{
Node oldLast = last;
last = new Node();
last.item = item;
last.next = null;
//special cases for empty queue
if(isEmpty())
{
first = last;
}
else
{
oldLast.next = last;
}
}
public String dequeue()
{
String item = first.item;
first = first.next;
//special cases for empty queue
if(isEmpty())
{
last = null;
}
return item;
}
}