DEV Community

Cover image for A Comprehensive Guide to Queue Data Structure
Guilherme Batista
Guilherme Batista

Posted on

A Comprehensive Guide to Queue Data Structure

A queue is a data structure that allows the addition and removal of elements with a specific rule: the first element to be added is the first one to be removed. This rule follows the FIFO (First-In, First-Out) order, which means that the first item to enter the queue is also the first to leave. Queues are similar to a real-life queue of people, where the person who arrives first is the one to be served first.

Now, let's look at a Java code example that represents a simple implementation of a queue:

public class Queue {
    private int size;
    private double[] data;
    private int head;
    private int tail;
    private int length;

    private boolean isEmpty() {
        return this.length == 0;
    }

    private boolean isFull() {
        return this.tail == this.size - 1;
    }

    public Queue(int size) {
        this.size = size;
        this.data = new double[size];
        this.head = 0;
        this.tail = -1;
        this.length = 0;
    }

    public void enqueue(double value) {
        if (this.isFull()) {
            throw new RuntimeException("queue overflow");
        }

        this.tail++;
        this.data[this.tail] = value;
        this.length++;
    }

    public void dequeue() {
        if (this.isEmpty()) {
           throw new RuntimeException("empty queue"); 
        }

        this.head++;
        this.length--;
    }
}
Enter fullscreen mode Exit fullscreen mode

In the code above we have a simple queue structure with 5 properties:

  • size: The queue size
  • data: An array of double that will store the queue data
  • head: The position of the first element of the queue
  • tail: The position of the last element of the queue
  • length: The queue length

And we have 2 main methods:

  • enqueue: This method verifies if the queue is full if it's true an exception will be thrown saying the queue is full, if it's false now the tail position will be the next, and we will store the data in that position and increment the length
  • dequeue: This method verifies if the queue is empty if it's true an exception will be thrown saying the queue is empty, if it's false now the head of the queue is the next position and the length is decreased.

Note that we didn't really remove the element of the queue just changed the head and tail positions.

enqueue Usage example:

Queue queue = new Queue(3);
queue.enqueue(10); // index 0
queue.enqueue(20); // index 1
queue.enqueue(30); // index 2
// head is 0 and tail is 2
Enter fullscreen mode Exit fullscreen mode

dequeue Usage example:

Queue queue = new Queue(3);
queue.enqueue(10); // index 0
queue.enqueue(20); // index 1
queue.enqueue(30); // index 2
// head is 0 and tail is 2
queue.dequeue();
// after dequeue head is 1 and tail is 2
Enter fullscreen mode Exit fullscreen mode

Top comments (0)