public class Queue implements QueueInterface {
private class Node {
Object data;
Node next;
Node(Object data) {
this.data = data;
// this.next = next;
}
}
private Node head;
private Node tail;
private int count;
// isEmpty()
// pre: none
// post: returns true if this Queue is empty, false otherwise
public boolean isEmpty() {
return head == null;
}
// enqueue()
// adds newItem to back of this Queue
// pre: none
// post: !isEmpty()
public void enqueue(Object newItem) {
Node p = new Node(newItem);
if (isEmpty()) {
head = tail = p;
} else {
tail.next = p;
p = tail;
}
}
// toString()
// overrides Object's toString() method
public String toString() {
String s = "";
for (Node N = head; N != null; N = N.next) {
s += N.data + " ";
}
return s;
}
}
当我使用队列测试java文件。我试着把数字2、5、7和10排在队列中。然而,当我想打印出元素时,它只显示第一个和最后一个元素。
我不知道这是我的toString函数工作不正确还是它是enqueue . .
enqueue
应该将tail
更新为新进入队列的元素:
public void enqueue(Object newItem) {
Node p = new Node(newItem);
if (isEmpty()) {
head = tail = p;
} else {
tail.next = p;
tail = p; // instead of p = tail;
}
}
public String toString() {
// Use a StringBuilder instead of String
StringBuilder sb = new StringBuilder();
for (Node N = head; N != null; N = N.next) {
sb.append(N.data + " ");
}
return sb.toString();
}