gpt4 book ai didi

Java代码错误链表

转载 作者:行者123 更新时间:2023-11-30 03:13:25 24 4
gpt4 key购买 nike

嗨,自从我编写 java 以来已经有一段时间了,我似乎找不到这段代码有什么问题。我正在实现从链表中删除一个节点,但我的程序无法编译。我不断收到:

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

Node head = new Node();

我的 main 方法中的所有新 Node() 实例都有错误。

public class NodeDelete{

class Node {
int data;
Node next;

public Node(){ }
}


Node Delete(Node head, int position) {
// Complete this method
int index = 0;
Node current = head;
if (position == 0 ){
head = head.next;
}
else{
while (index < (position - 1)){
current = current.next;
}
current.next = current.next.next;
}
return head;
}

public static void main(String[] args) {
Node head = new Node();
head.data = 0;

Node node1 = new Node();
node1.data = 1;

Node node2 = new Node();
node2.data = 2;

head.next = node1;
node1.next = node2;
}
}

最佳答案

要么使Node类静态。 NodeDelete类中取出Node类。这将解决问题。

Node 类是 NodeDelete非静态内部类,因此它就像 NodeDelete< 的成员 类。要访问静态上下文中的任何成员,需要类的实例。这就是为什么您会在此处收到编译时错误

注意:您在Node中定义的构造函数与默认构造函数相同。所以没必要定义它。这是多余的。

使 Node 类静态:

static class Node {
int data;
Node next;

public Node(){ } // This is same as the default constructor. So this can be remove.
}

从 NodeDelete 类中取出相同的实现。

关于Java代码错误链表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33180968/

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