在链表末尾添加节点(java)

在链表末尾添加节点(java),java,linked-list,Java,Linked List,这是我的链表代码(不是主代码)。“addLast”方法给了我以下错误,我不确定如何解决它:“不能从静态上下文引用非静态变量”。 这是关于这一行的:返回新节点(x,null); 对于如何解决这个问题,我非常感谢您的帮助。多谢各位 public class LinkedList { private class Node { int item; Node link; public Node () {

这是我的链表代码(不是主代码)。“addLast”方法给了我以下错误,我不确定如何解决它:“不能从静态上下文引用非静态变量”。 这是关于这一行的:返回新节点(x,null); 对于如何解决这个问题,我非常感谢您的帮助。多谢各位

public class LinkedList
{

  private class Node 
    { 
        int item;
        Node link;

        public Node ()
        {
            item = Integer.MIN_VALUE;
            link = null;

        }

        public Node (int x, Node p)

        {  
            item = x;
            link = p;

        }

    } //End of node class


    private Node head;


    public LinkedList()
    {
        head = null;
    }

    //adds a node to the start of the list with the specified data
    //added node will be the first node in the list

    public void addToStart(int x)
    {
        head = new Node(x, head);
    }


    //adds a number at end of list 
    public static Node addLast(Node header, int x)
    { 
        // save the reference to the header so we can return it. 
        Node ret = header; 

        // check base case, header is null. 
        if (header == null) { 
            return new Node(x, null); 
        } 

        // loop until we find the end of the list 
        while ((header.link != null)) { 
            header = header.link; 
        } 

        // set the new node to the Object x, next will be null. 
        header.link = new Node(x, null); 
        return ret; 
    }


    //displays the list
    public void printList()
    {
        Node position = head;
        while(position != null)
        {
            System.out.print(position.item + " ");
            position = position.link;
        }

        System.out.println();
    }
}

以下是两种解决方案:

节点
设为静态嵌套类:

private static class Node { ... }
或者,将
addLast
方法作为实例方法:

public Node addLast(Node header, int x) { ... }

addLast
中删除
static
限定符——它必须是非静态的,才能在末尾添加一个列表。它也不应该接受(或返回)一个
节点,因为
节点
是一个私有嵌套类,所以该类之外的代码不知道(或不关心)节点是什么,所以不能传递

public void addLast(int x) {
    if (head == null) head = new Node(x, null);
    else {
        Node p = head;
        while (p.link != null) p = p.link;
        p.link = new Node(x, null); } }

答案在错误行中:

无法从静态上下文引用非静态变量


删除方法
addLast
static

public Node addLast(Node header, int x) 
{
  ....
}

它不需要是静态嵌套类,尽管这样做可能有意义。使其非静态与OPs问题无关。@ChrisDodd True,这不是绝对必要的,但
节点
独立于
链接列表
似乎更符合逻辑。这取决于您想对列表执行什么操作。将其设置为非静态允许节点引用其所包含列表的标题,这可能对某些算法有用。我不能这样做,因为addLast必须是静态的,我的main才能访问它。不,你的main只需要一个
LinkedList
就可以在--
list=new LinkedList()上调用
addLast
;列表。addLast(5);列表。addLast(6)…你能解释一下for循环吗?它扫描到列表的末尾。当我输入你的代码时,重写为一个
,使它更清晰,因为行头=新节点(x);它给出了以下错误:没有为节点(int)找到合适的构造函数