2017-10-11 112 views
2

我試圖添加一個節點到我的鏈表的末尾,當我到達else語句時,我得到一個空指針異常並嘗試將problem.rear.next設置爲我添加的新節點。出於某種原因,當我嘗試將rear.next指針設置爲新節點時,會彈出異常。添加一個節點,然後鏈接列表的末尾,有一個後端和開始指針

爲了澄清,

的BigIntegerList是也被鏈接,通過單獨整數連接在一起代表一個大的整數列表節點的鏈接列表。大整數列表定義了一個「開始」和「後面」節點。BigInteger節點爲數據定義了「x」,爲下一個節點指向了列表中的下一個節點。

此外,

problem.n表示要讀取BigIntegers的數字,該方法從一個文本文件中讀取,被讀取之後的實際BigIntegers第一個數字閱讀狀態很多大整數怎麼回事

任何想法表示歡迎,因爲我非常卡住....

BigIntegerList problem; 
    LinkedList x; 
    BigIntegerNode curr; 

    problem = new BigIntegerList(); 
    //get value of first line stating #of bigInts to read in 
    problem.n = LinkedList.readInteger(in); 
    //read big ints from text file based on first number passed, n 
    for(int i=0; i<problem.n;i++) 
    { 
    x = new LinkedList(); 
    x.readBigInteger(in); 
    //case that the list is empty 
    if(problem.n<1) 
    { 
     problem.start = new BigIntegerNode(x,null); 
     problem.rear = problem.start; 
    //list is not empty, add nodes to rear 
    }else 
    { 
     curr = new BigIntegerNode(x,null); 
     problem.rear.next = curr; -----> this is where i get a nullpointer.... 
     problem.rear = curr; 
    } 
    } 
    return problem; 
+2

看看你的代碼,它似乎'if(problem.n <1)'總是評估爲'false'。因此,你的'else'塊總是用'problem.rear'仍然是'null'執行。您是否嘗試過使用您的調試器? – dave

回答

0

正如@戴夫指出,改變if (problem.n < 1)

If (i < 1) { 

problem.n是循環將執行的迭代的總數,即常量。 i是循環的計數器。它將在第一次迭代中設置爲0,然後設爲1,2,3,...,(problem.n)-1

由於您希望if語句在第一次迭代中計算爲true ,讓它看看我而不是problem.n

+0

你介意多說一點嗎?爲了可能閱讀此答案的新用戶。 – Shirkam

相關問題