DEV Community

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

Posted on • Edited on

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:

Top comments (0)