2017-10-11 111 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

相关问题