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).
Enqueue
: inserts an element to the end of the queueDequeue
: removes an element from the start of the queueIs empty
: checks if the queue is emptyTop
: returns the first element of the queuepublic 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;
}
}