Java队列.此程序结果为空



我正在学习队列数据结构。我想用链接列表创建队列。程序输出:队列空-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 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());
}
}

您正在覆盖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);

您正在创建一个新的 local 命名 root的变量,该变量隐藏了静态 field root。相反,您应该写:

root=new Node(x);

如果您具有隐藏静态字段root的局部变量root,也可以通过使用类名来访问静态字段:

QueQueLinked.root = new Node(x)

在这种情况下,您应该重新考虑变量名称。

相关内容

最新更新