我知道java是按值傳遞的。對於鏈表數據結構,方法size()和size1()之間有什麼區別?我認爲,size1()中的頭部和下一個參考點也是一樣的。但結果卻是差別解釋Java中的Linked List數據結構
public class IntList {
int item;
IntList next;
public IntList(int item, IntList next){
this.item = item;
this.next = next;
}
public int size(){
int size = 1;
while (next !=null){
size++;
next = next.next;
}
return size;
}
public int size1(){
int size = 1;
IntList head = next;
while (head != null){
size++;
head = head.next;
}
return size;
}
public static void main(String[] args) {
IntList L = new IntList(1,null);
L = new IntList(2,L);
L = new IntList(3,L);
L = new IntList(10,L);
L = new IntList(20,L);
System.out.println(L.size());
}
}
我感到困惑參照裝置在java中。
是結果不同,如果你調用'尺寸1()'第一? – shmosel
是的。 size()將修改L;但size1()不會改變L – jason