【问题标题】:an enclosing instance that contains Queue.Node is required需要包含 Queue.Node 的封闭实例
【发布时间】:2013-06-07 00:27:51
【问题描述】:

所以我正在研究二叉搜索树,需要进行级别顺序遍历。我将打印出同一级别的所有键。

我现在遇到的问题是我需要创建一个 FIFO 队列。我创建了队列,但是当我尝试将节点添加到队列时,我不断收到an enclosing instance that contains Queue.Node is required 错误消息。有人可以帮我解决我做错了什么。

这是我目前的水平顺序遍历。

public void LevelOrder_Traversal(BST_Node node){
    Queue temp=new Queue();


    Queue.Node newNode=new Queue.Node();

    temp.enqueue(node);

这是我的队列类

public class Queue{
public class Node{
    private Integer key;
    private Node next;

    public Node(){
        this.key=null;
        this.next=null;
    }

    public Node(int key){
        this.key=key;
        this.next=null;
    }
}

int size;
Node head;

public Queue(){
    head=new Node();
    size=0;
}

public void enqueue(Node node){
    if(size==0){
        head=node;
    }

    Node curr=head;
    while(curr.next!=null){
        curr=curr.next;
    }
    curr.next=node;
    size++;
}

public Node dequeue(){
    Node temp=head;
    head=head.next;
    size--;

    return temp;
  }
}

我发现了一些与我正在做的类似的其他帖子,但我并没有真正了解它们。如果有人能很好地解释我做错了什么以及为什么错了,那就太好了。我是否需要扩展 Queue 类或类似的东西?

【问题讨论】:

标签: java linked-list queue binary-search-tree fifo


【解决方案1】:

这是因为您的 Node 内部类是非静态的。 Java 中的非静态类具有对其封闭类的隐式引用,因此它们必须由外部类的实例方法实例化。像这样实例化它

Queue.Node newNode=new Queue.Node();

无效,即使 Node 类是 public

使用static 关键字声明它以解决此编译问题:该类可以逻辑地生成static,因为它的方法不需要知道封闭的Queue 类。

【讨论】:

  • 好的,这是有道理的。如何将队列节点转换为 bst 节点?
  • @k3vyw3vy 队列节点有一个 next 链接;一个 BST 节点有两个链接 - rightleft
  • 好的,所以它不起作用。是否可以将 BST 节点添加到队列链接列表中,或者有更简单的方法吗?
  • @k3vyw3vy 您的 BST 类应该与队列类分开。要进行级别顺序遍历,您需要将 BST 的节点添加到队列中,因此您需要队列和 BST。节点的key应该是BST节点,而不是Integer
【解决方案2】:

您声明:

public class Queue {
    public class Node {

这意味着要使Node 实例存在,您必须拥有Queue 的实例。因此消息:“需要包含 Queue.Node 的封闭 [Queue in this case] 实例”。

为了获得具有这种设计的Node,相当笨拙的语法是:

final Queue queue = new Queue();
final Node node = queue.new Node();

一般来说,如果实际上需要 Node 具有完全相关的 Queue,则可以使用此设计。我从未见过...除了 private 内部类。

但如果您的Node 类可以独立创建Queue,则它必须声明为static

public class Queue {
    public static class Node { // <-- note the 'static'

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-05-16
    • 2011-11-28
    • 1970-01-01
    • 2013-12-26
    • 2012-11-20
    • 1970-01-01
    • 1970-01-01
    • 2011-12-12
    相关资源
    最近更新 更多