Java队列。此程序结果为空。
我正在学习队列数据结构。我想用链表创建队列。我想编程输出:10 20 程序输出:队列为空-1队列为空-1 我在哪里犯错 代码如下所示:Java队列。此程序结果为空。,java,data-structures,linked-list,queue,Java,Data Structures,Linked List,Queue,我正在学习队列数据结构。我想用链表创建队列。我想编程输出:10 20 程序输出:队列为空-1队列为空-1 我在哪里犯错 代码如下所示: class Node { int x; Node next; Node (int x){ this.x=x; next=null; } } public class QueQueLinked { static Node root=null; static Node latest=null; public static
class Node {
int x;
Node next;
Node (int x){
this.x=x;
next=null;
}
}
public class QueQueLinked {
static Node root=null;
static Node latest=null;
public static void enque(int x){
if(root==null){
Node root=new Node(x);
root.x=x;
root.next=null;
latest=root;
}
else{
latest.next=new Node(x);
latest=latest.next;
latest.next=null;
}
}
public static int deque(){
if(root==null){
System.out.println("Queque empty");
return -1;
}
int value=root.x;
root=root.next;
return value;
}
public static void main(String[] args) {
enque(10);
enque(20);
System.out.println(deque());
System.out.println(deque());
}
}
您正在覆盖根变量。您需要执行以下操作:
public static void enque(int x){
if(root==null){
root=new Node(x);
root.x=x;
root.next=null;
latest=root;
}
您正在覆盖根变量。您需要执行以下操作:
public static void enque(int x){
if(root==null){
root=new Node(x);
root.x=x;
root.next=null;
latest=root;
}
您的错误在这一行:
Node root=new Node(x);
您正在创建一个名为root
的新local变量,该变量隐藏静态字段root
。相反,你应该写:
root=new Node(x);
如果您有一个局部变量root
,它隐藏了静态字段root
,您也可以通过在静态字段前面加上类名来访问它:
QueQueLinked.root = new Node(x)
但是,在这种情况下,您应该重新考虑变量名。您的错误在这一行:
Node root=new Node(x);
您正在创建一个名为root
的新local变量,该变量隐藏静态字段root
。相反,你应该写:
root=new Node(x);
如果您有一个局部变量root
,它隐藏了静态字段root
,您也可以通过在静态字段前面加上类名来访问它:
QueQueLinked.root = new Node(x)
但是,在这种情况下,您应该重新考虑变量名