将值添加到链接列表错误[Java]

时间:2018-12-30 21:39:14

标签: java

因此,在同一文件中创建NodeList类并尝试通过main方法向新创建的List对象添加值之后,出现此错误:

 [line: 60]
 Error: No enclosing instance of type List is accessible. Must qualify the allocation
 with an enclosing instance of type List (e.g. x.new A() where x is an instance of List).

如果我将Node类放在一个单独的文件中,并在main类中创建我的Node方法并执行相同的命令,那么它将正常工作。所以我很好奇为什么会发生此问题。

这是我的代码

public class List{
  Node head;

  public class Node{
    Node next;
    int data;   

    Node(int data, Node next){
      this.data = data;
      this.next = next;
    }

    Node(int data){
      this.data = data;
    }

    public Node getNode(Node n){
      return n;
    }
  }

  public void add(Node n){
    if(head == null){
      head = n;
    }
    else{
      Node t = head;
      while(t.next!=null){
        t=t.next;
      }
      t.next = n;
    }
  }

  public void add(int data){
    Node n1 = new Node(data);

    if(head==null){
      head = n1;
    }
    else{
      Node t = head;
      while(t.next!=null){
        t = t.next;
      }
      t.next = n1;
    }
  }

  public void show(){ 
    Node t = head;
    while(t != null){
      System.out.println(t.data);
      t = t.next;
    }
  }

  public static void main(String[] args){

    Node a1 = new Node(65);
    List newList = new List();
    newList.add(a1);
    newList.show();

  }
}

0 个答案:

没有答案