4 回答

TA貢獻1799條經(jīng)驗 獲得超8個贊
您可以通過添加一個額外的私有方法來調(diào)整它,但這并不是特別容易推理。除非絕對必要,否則我會避免這樣做。
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條經(jīng)驗 獲得超9個贊
向 IntNode 類添加一個 size 方法,并從 SLList size 方法訪問它以計算列表的整個大小。以下代碼片段是不言自明的。有關(guān)嵌套類的更多信息,請參閱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條經(jīng)驗 獲得超7個贊
size()是一種方法SLList,不是IntNode。您可以參考內(nèi)部的外部類方法IntNode,如下所示:
public class SLList {
public class IntNode {
...
public int size() {
return SLList.this.size();
}
}
...
public static int size() {
...
}
}
添加回答
舉報