gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 06:22:50 25 4
gpt4 key购买 nike

这是我的链表代码(不是主代码)。方法“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();
}
}

最佳答案

这里有两个解决方案:

使 Node 成为静态嵌套类:

private static class Node { ... }

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

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

关于java - 在链表末尾添加节点(java),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27207357/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com