DEV Community

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

Posted on • Edited 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:

import java.util.LinkedList;
import java.util.List;

public class Queue<T> {
    private List<T> data;
    private int length;

    public Queue() {
        this.data = new LinkedList<>();
        this.length = 0;
    }

    public void enqueue(T value) {
        this.data.add(value);
        this.length++;
    }

    public T dequeue() {
        if (this.length == 0) {
            throw new RuntimeException("Empty queue");
        }

        this.length--;
        return this.data.remove(0);
    }
}
Enter fullscreen mode Exit fullscreen mode

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

  • data: A List to store the queue data
  • length: The queue length

And we have 2 main methods:

  • enqueue: This method adds the new element to the List and increments the length variable by 1.
  • 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 the length variable is decreased by 1, then the first element of the list is removed and returned.

enqueue Usage example:

Queue<Integer> queue = new Queue();
queue.enqueue(10); // index 0
queue.enqueue(20); // index 1
queue.enqueue(30); // index 2
Enter fullscreen mode Exit fullscreen mode

dequeue Usage example:

Queue<Integer> queue = new Queue();
queue.enqueue(10); // index 0
queue.enqueue(20); // index 1
queue.enqueue(30); // index 2

queue.dequeue();
// after dequeue the first element is removed
Enter fullscreen mode Exit fullscreen mode

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay