So here is my Queue interface:
public interface Queue<E> {
/**
* Add an item to the rear of the queue.
*
* @param item
* Item to be added.
*/
public void enqueue(E item);
/**
* Remove and return the item at the front of the queue.
*
* @return The item that was removed.
*/
public E dequeue();
/**
* @return The item at the front of the queue.
*/
public E frontValue();
/**
* @return How many elements are in the queue.
*/
public int length();
/**
* Remove all the items in the queue.
*/
public void clear();
}
And here is my actual implementation:
public class LinkedQueue<E> implements Queue<E> {
private SinglyLinkedListNode<E> front;
private SinglyLinkedListNode<E> rear;
private int size;
/**
* Create a new LinkedQueue object.
*/
public LinkedQueue() {
this.init();
}
private void init() {
// only one object is constructed
this.front = this.rear = new SinglyLinkedListNode<E>(null, null);
this.size = 0;
}
@Override
public void enqueue(E value) {
this.rear.setNextNode(new SinglyLinkedListNode<E>(value, null));
this.rear = this.rear.getNextNode();
this.size++;
}
@Override
public E dequeue() {
if (this.size == 0) {
throw new IllegalStateException("In method dequeue of class "
+ "LinkedQueue the linked queue is empty can cannot"
+ " be dequeued");
}
E item = this.front.getNextNode().getValue();
this.front.setNextNode(this.front.getNextNode().getNextNode());
if (this.front.getNextNode() == null) {
this.rear = this.front;
}
this.size--;
return item;
}
@Override
public E frontValue() {
if (this.size == 0) {
throw new IllegalStateException("In method frontValue of class "
+ "LinkedQueue the linked queue is empty");
}
return this.front.getNextNode().getValue();
}
@Override
public int length() {
return this.size;
}
@Override
public void clear() {
this.init();
}
/**
* Creates a easy to read String representation of the linked queue's
* contents.
*
* Example: < 1 2 3 4 5 6 >
*/
public String toString() {
StringBuilder linkedQueueAsString = new StringBuilder();
linkedQueueAsString.append("< ");
System.out.println("front.getNextNode: " + this.front.getNextNode());
for (SinglyLinkedListNode<E> node = this.front.getNextNode(); node != null; node = node.getNextNode()) {
linkedQueueAsString.append(node.getValue());
System.out.println(node.getValue() + ",");
linkedQueueAsString.append(" ");
}
linkedQueueAsString.append(">");
return linkedQueueAsString.toString();
}
}