我想用Java编写一个enqueue(elem),所以我编写了以下模块:
public class Node{
public int e;
Node next;
public Node(int e){
this.e=e;
}
}
现在我想使用链接列表来存储我的元素,所以我创建了一个带有 enqueue() 函数的类,如下所示:
public class Queue{
Node q; //represents a queue
Node first;
public void enqueue(int n){
Node t=new Node(n); //represents a temporal node
if(q==null){
first=t;
}
else{
t.next=first;
t=first;
}
q=t; //to store the node into the queue
}
}
但是当我想打印队列的元素时:
public void print(){
Node current=first;
while (current!=null){
System.out.println(current.e);
current=current.next;
}
}
它只打印我输入的第一个元素,例如,如果我输入 10,20,30,40,它只打印 10。我做错了什么?
谢谢
最佳答案
您的队列类代码应如下所示。节点 first 将是第一个元素,q 将是最后一个元素。
public class Queue{
Node q;
Node first;
public void enqueue(int n){
Node t=new Node(n);
if(q==null){
first=t;
}
else{
q.next=t;
}
q=t;
}
public void print(){
Node current=first;
while (current!=null){
System.out.println(current.e);
current = current.next;
}
}
}
关于java - Java中的队列编程不会更新队列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56314748/