简体   繁体   English

在while循环中到达时条件始终为true

[英]Condition always true when reached in while loop

I created a method to insert a Linked List node in the correct place of a sorted (increasing) linked list but I am having some problems. 我创建了一个方法来将链接列表节点插入排序(增加)链表的正确位置,但我遇到了一些问题。

public static void sortedInsert(LinkedListNode root, int value) {
        LinkedListNode newNode = new LinkedListNode(value);
        if (root == null || root.data >= value) {
            newNode.next = root;
        } else {
            LinkedListNode curr = root;
            while (curr.next.data < value && curr.next != null) {
                curr = curr.next;
            }
            newNode.next = curr.next;
            curr.next = newNode;
        }
    }

errors: 错误:

Exception in thread "main" java.lang.NullPointerException
    at LinkedLists.LinkedListProblems.sortedInsert(LinkedListProblems.java:188)

The curr.next != null portion is highlighted in intellij so I'm assuming that is causing the error. curr.next != null部分在intellij中突出显示,所以我假设是导致错误。 This error only occurs when the value I added is bigger than the last value of the sorted linked list 仅当我添加的值大于已排序链接列表的最后一个值时,才会出现此错误

However when the iterate to the last node of the linked list and the value of that node is still less than the value of the parameter. 但是,当迭代到链表的最后一个节点并且该节点的值仍然小于参数的值时。 Shouldn't that exit the while loop? 不应该退出while循环吗?

I think the problem is here 我认为问题出在这里

while (curr.next.data < value && curr.next != null) {
  curr = curr.next;
}

You are testing in the wrong order, first check for null - 您正在以错误的顺序进行测试,首先检查是否为null -

while (curr.next != null && curr.next.data < value) {
  curr = curr.next;
}

Otherwise when curr.next is null it will have already tested curr.next.data < value which will throw a NullPointerException . 否则,当curr.nextnull ,它将测试curr.next.data < value ,这将抛出NullPointerException

看起来你的第一个应该是!= null,它应该是&&,否则即使root为null也可以对root.data进行求值。

if (root != null && root.data >= value) {

You are getting an exception on that line because cur.next.data gets tested before cur.next!=null . 您在该行上获得异常,因为cur.next.datacur.next!=null之前进行了测试。

Swap them over and the && will be short circuited correctly avoiding the exception. 将它们交换掉, &&将被正确地短路,避免异常。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM