在链接列表的末尾添加一个节点(java)

时间:2014-11-29 21:31:04

标签: java linked-list

这是我的链表(不是主要)的代码。方法“addLast”给我以下错误,我不知道如何解决它:“无法从静态上下文引用非静态变量”。 它正在讨论这一行:return new Node(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();
    }
}

3 个答案:

答案 0 :(得分:1)

以下是两个解决方案:

使Node成为静态嵌套类:

private static class Node { ... }

或者,将addLast方法设为实例方法:

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

答案 1 :(得分:0)

static删除addLast限定符 - 它必须是非静态的才能有一个列表添加到结尾。它也不应该(或返回)Node,因为Node是一个私有嵌套类,所以这个类之外的代码不知道(或关心)Node是什么,所以不能让一个人通过。

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); } }

答案 2 :(得分:0)

答案在错误行中:

  

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

删除方法static的{​​{1}}。

addLast
相关问题