Java 使用链表执行队列,Enqueue()不起作用
当我使用队列测试java文件时。我试着把数字2、5、7和10排成一列。但是,当我想打印出元素时,它只显示第一个和最后一个元素Java 使用链表执行队列,Enqueue()不起作用,java,linked-list,Java,Linked List,当我使用队列测试java文件时。我试着把数字2、5、7和10排成一列。但是,当我想打印出元素时,它只显示第一个和最后一个元素 我不知道是我的toString函数工作不正常还是排队。-.排队应将尾部更新为新排队的元素: public class Queue implements QueueInterface { private class Node { Object data; Node next; Node(Object data) { this.da
我不知道是我的toString函数工作不正常还是排队。-.排队应将
尾部更新为新排队的元素:
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;
}
}
p、 让我们使用StringBuilder,而不是String(在toString中)@manouti!但是排队的人不应该按顺序打印吗?比如说:排队它应该做2 3,而不是3 2它仍然是错的。应该是tail.next=p;尾=p代码>OP有tail.next=p代码>部分正确。@DavidConrad我让它打印队列,但它打印的结果相反。trynna按顺序打印出来。-@DavidConrad你说得对。只需更改一行代码:)Post updated。
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();
}