DEV Community

Cover image for Data Structure In Java: Dynamic Queue
luthfisauqi17
luthfisauqi17

Posted on • Edited on

2 1

Data Structure In Java: Dynamic Queue

import java.util.EmptyStackException;

public class QueueDynamic<T> {
    private class QueueNode {
        private T data;
        private QueueNode next;
        private QueueNode(T data) {
            this.data = data;
            this.next = null;
        }
    }

    private QueueNode first;
    private QueueNode last;

    public QueueDynamic() {
        this.first = this.last = null;
    }

    public QueueDynamic(T data) {
        this.first = this.last = new QueueNode(data);
    }

    public void add(T data) {
        QueueNode temp = new QueueNode(data);
        if (this.last != null) {
            this.last.next = temp;
        }
        last = temp;
        if (this.first == null) {
            this.first = this.last;
        }
    }

    public T remove() {
        if (first == null) throw new EmptyStackException();
        T data = this.first.data;
        this.first = this.first.next;
        if (this.first == null) {
            this.last = null;
        }
        return data;
    }

    public T peek() {
        if (first == null) throw new EmptyStackException();
        return this.first.data;
    }

    public boolean isEmpty() {
        return this.first == null;
    }
}
Enter fullscreen mode Exit fullscreen mode

Sources and Images:

Heroku

Build apps, not infrastructure.

Dealing with servers, hardware, and infrastructure can take up your valuable time. Discover the benefits of Heroku, the PaaS of choice for developers since 2007.

Visit Site

Top comments (0)

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

Rather than just generating snippets, our agents understand your entire project context, can make decisions, use tools, and carry out tasks autonomously.

Read full post

👋 Kindness is contagious

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

Okay