Linear Data Structures_ Queues Cheatsheet _ Codecademy
Linear Data Structures_ Queues Cheatsheet _ Codecademy
Queues
The Java Queue class should include two helper public boolean hasSpace() {
methods to determine what actions can be taken with
return this.size < this.maxSize;
the queue:
.hasSpace() returns a boolean }
representing whether or not there is room left
in a bounded queue
public boolean isEmpty() {
.isEmpty() returns a boolean
representing whether or not the queue is empty return this.size == 0;
These methods use the Queue instance variables, }
size and maxSize , to determine what value
should be returned.
Java Queue: enqueue()
The .enqueue() method of the Java Queue public void enqueue(String data) {
class is used to add new data to the queue. It takes a
if (this.hasSpace()) {
single argument, data , which is added to the end of
the queue using the LinkedList method this.queue.addToTail(data);
.addToTail() . A print statement can be this.size++;
included to describe the addition. The method then System.out.println("Added " +
increases size and throws an error if the queue is
data + "! Queue size is now " +
full. The helper method .hasSpace() is used to
verify if the queue is full. this.size);
} else {
throw new Error("Queue is
full!");
}
}
The .peek() method of the Java Queue class public String peek() {
allows us to see the element at the head of the queue
if (this.isEmpty()) {
without removing it. If a head exists (the queue is not
empty), this method returns the data in the head. return null;
Otherwise, it returns null . This is verified using the } else {
helper method .isEmpty() . return this.stack.head.data;
}
}
Print Share