4 回答

TA贡献1799条经验 获得超8个赞
您可以通过添加一个额外的私有方法来调整它,但这并不是特别容易推理。除非绝对必要,否则我会避免这样做。
class SLList {
public class IntNode {
public int item;
public IntNode next;
public IntNode(int i, IntNode n) {
item = i;
next = n;
}
private int theSize()
{
return size();
}
}
private IntNode first;
public SLList(int x) {
first = new IntNode(x, null);
}
public int size() {
if (first.next == null) {
return 1;
}
return 1 + first.next.theSize();
}
}

TA贡献1890条经验 获得超9个赞
向 IntNode 类添加一个 size 方法,并从 SLList size 方法访问它以计算列表的整个大小。以下代码片段是不言自明的。有关嵌套类的更多信息,请参阅https://www.programiz.com/java-programming/nested-inner-class
public class SLList {
public class IntNode {
public int item;
public IntNode next;
public IntNode(int i, IntNode n) {
item = i;
next = n;
}
public int size() {
IntNode tmp = next;
if (tmp == null) {
return 1;
}
return 1 + tmp.size();
}
}
private IntNode first;
public SLList(int x) {
first = new IntNode(x, null);
}
public int size() {
if (first == null)
return 0;
return first.size();
}
public static void main(String[] args) {
SLList list = new SLList(10);
list.first.next = list.new IntNode(20, null);
list.first.next.next = list.new IntNode(30, null);
list.first.next.next.next = list.new IntNode(40, null);
System.out.println(list.size());
}
}

TA贡献1852条经验 获得超7个赞
size()是一种方法SLList,不是IntNode。您可以参考内部的外部类方法IntNode,如下所示:
public class SLList {
public class IntNode {
...
public int size() {
return SLList.this.size();
}
}
...
public static int size() {
...
}
}
添加回答
举报