import java.util.LinkedList;
import java.util.List;
import java.util.NoSuchElementException;
public class MyLinkedList {
private ListNode head;
private int size;
//inner class for ListNode
private class ListNode {
private Object data;
private ListNode next;
private ListNode(Object d) {
this.data = d;
this.next = null;
}
}
public MyLinkedList() {
this.head = new ListNode(null); //with a dummy head node
this.size = 0;
}
我尝试使用的方法是 Interleave,但我收到了该错误。
public static MyLinkedList interleave(MyLinkedList A, MyLinkedList B) {
MyLinkedList C = new MyLinkedList();
ListNode curA = A.head.next;
ListNode curB = B.head.next;
ListNode curC = C.head;
boolean grabFromA = true;
while (curA != null && curB != null) {
if (grabFromA) {
curC.next = new ListNode(curA.data);
curA = curA.next;
}
else {
curC.next = new ListNode(curB.data);
curB = curB.next;
}
curC = curC.next;
grabFromA = !grabFromA; // Flips grab from A
}
while (curA != null) {
curC.next = new ListNode(curA.data);
curA = curA.next;
curC = curC.next;
}
while (curB != null) {
curC.next = new ListNode(curB.data);
curB = curB.next;
curC = curC.next;
}
return C; //change this as you need.
}
我无法更改其是否静态,因为这是一项分配,如果我更改它,那么它会导致所有测试失败。所以如果有人能解释这一点那就太棒了。我尝试在作业中使用 add 方法,但它是非静态方法,因此我无法在此静态方法中调用它。
等效错误的一个较小示例是:
class MyLinkedList {
class ListNode {}
static void f() {
new ListNode();
}
}
IntelliJ 将错误报告为
'MyLinkedList.this' cannot be referenced from a static context
,javac 将其报告为:
T.java:5: error: non-static variable this cannot be referenced from a static context
new ListNode();
^
以下是两个可能的修复方法:
ListNode
成为 static
成员类,而不是非 static
内部类:private static class ListNode { ... }
new MyLinkedList().new ListNode(...)
第一个选项是我在这里推荐的选项,因为
ListNode
不引用封闭实例中的任何状态,并且不需要是内部类。
如果
ListNode
需要是非 static
内部类,则在这个类似问题的答案中有有关第二个选项的更多信息:How to instantiate non static inside class inside a static method?