Я включил все внутри моей toString, чтобы попытаться получить результат, который я хотел, но мне не повезло. Я пытаюсь получить этот результат:Работа с toString и очередью в Java
QUEUE TESTING
3
7
7
4
The size of the queue is: 3
The queue contains:
4 9 8
Но вместо этого, я получаю это:
QUEUE TESTING
3
7
7
4
The size of the queue is: 3
The queue contains:
9 8
И я не могу понять, почему четыре не возвращается с 9 и 8. Может кто-нибудь, пожалуйста, скажите мне, что происходит. Благодаря!
Вот код, я работаю с (прикрепленными файлами влево-аут):
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();' вместо того, чтобы начинать с узла 'head'? – gla3dr