https://s3-us-west-2.amazonaws.com/secure.notion-static.com/f6a2beda-978f-43e9-8a6b-fcc3ec81af30/queue-example.png

Queues are very similar to stacks, so, they're also very similar to arrays. Queue is another linear data structure that stores the element in a sequential manner. But, here, we use the FIFO method. Aka, First In First Out.

Just like in a stack, we are going to have a size for our queue, that is going to be her maximum number of elements. And, also, a index (our elements position).

Basic operations

Example

public class MyQueue {
    private ArrayList<String> queue = new ArrayList<String>();

    public void enqueue (String element) {
        this.queue.add(element);
    }

    public String dequeue () throws Exception {
        if (this.queue.size() <= 0) throw new Exception("The queue is empty");
        String oldestElement = this.queue.get(0);
        this.queue.remove(0);
        return oldestElement;
    }

    public String top () throws Exception {
        if (this.queue.size() <= 0) throw new Exception("The queue is empty");
        return this.queue.get(0);
    }

    public Boolean isEmpty() {
        return this.queue.size() <= 0;
    }
}