I've switched everything around within my toString to try and get the result I wanted, but I'm having no luck. I'm trying to get this result:
QUEUE TESTING
3
7
7
4
The size of the queue is: 3
The queue contains:
4 9 8
But instead, I'm getting this:
QUEUE TESTING
3
7
7
4
The size of the queue is: 3
The queue contains:
9 8
And I can't understand why the four isn't being returned with the 9 and 8. Can someone please tell me whats going on. Thanks!
Here's the code I'm working with (attached files left-out):
public class Murray_A06Q1 {
public static void main(String[] args) {
LinkedQueue<Integer> queue = new LinkedQueue<Integer>();
System.out.println("QUEUE TESTING");
queue.enqueue(3);
queue.enqueue(7);
queue.enqueue(4);
System.out.println(queue.first());
queue.dequeue();
queue.enqueue(9);
queue.enqueue(8);
System.out.println(queue.first());
System.out.println(queue.dequeue());
System.out.println(queue.first());
System.out.println("The size of the queue is: " + queue.size());
System.out.println("The queue contains:\n" + queue.toString());
}
public static class LinkedQueue<T> implements QueueADT<T> {
private int count;
private LinearNode<T> head, tail; //front, back
// Constructor
public LinkedQueue() {
count = 0;
head = tail = null;
}
// Adds the specified element to the tail of this queue.
public void enqueue(T element) {
LinearNode<T> node = new LinearNode<T>(element);
if (isEmpty())
head = node;
else
tail.setNext(node);
tail = node;
count++;
}
//Removes the element at the head of this queue and returns a
public T dequeue() throws EmptyCollectionException {
if (isEmpty())
throw new EmptyCollectionException("queue");
T result = head.getElement();
head = head.getNext();
count--;
if (isEmpty())
tail = null;
return result;
} // End of dequeue
// first() throws EmptyCollectionException
public T first() throws EmptyCollectionException {
return head.getElement();
}
// Beginning of isEmpty()
public boolean isEmpty() {
if(count == 0){
return true;
}
else {
return false;
}
} // End of isEmpty()
// Beginning of size()
public int size() {
return count;
}
// Begin of toString() method
public String toString() {
if (isEmpty()) {
return " ";
}
StringBuilder sb = new StringBuilder();
LinearNode<T> next = head.getNext();
while(next != null){
sb.append(" ").append(next.getElement());
next = next.getNext();
}
return sb.toString();
} // End of toString method
}
}
head.getNext();instead of starting with the nodehead?