我想實現鏈接列表。 因此,我有這個一流的,所謂的名單,它代表一個元素鏈接列表神祕
package list;
/**
* Linked list with int values.
*
* The empty list is represented by a null reference.
*/
public class List {
public int value;
public List next;
/**
* Creates a new list
*
* @param value value of the head of the list
* @param next reference to rest of the list; may be null
*/
public List(int value, List next)
{
this.value = value;
this.next = next;
}
}
,幷包含以下方法
public static int size(List list)
{
if(list==null) return 0;
else return size(list.next)+1;
}
到目前爲止一切正常鏈表類本身。但是,如果我嘗試
public static int size(List list)
{
if(list.next==null) return 1;
else return size(list.next)+1;
}
我得到一個NullPointerException ...... 我不知道爲什麼這不應該因爲list.next工作應該在一個點是空指針引用,並結束遞歸。 因此不應調用size(null.next)。
我的英語不好道歉,我的任何幫助
您將'list.next'傳遞給'size(..)',但size(..)'檢查list.next'。 'list'的可能值是什麼? –
我真的不知道評論的問題,但列表的值是null(List list = null)或這個(列表本身) – user2351468
所以如果'list == null'如何'list.next'表現? –