gpt4 book ai didi

java - 链表循环潜在异常

转载 作者:行者123 更新时间:2023-12-02 12:21:12 24 4
gpt4 key购买 nike

下面是检测链表是否包含循环的代码:

  public static boolean containsCycle(LinkedListNode firstNode) {

// start both runners at the beginning
LinkedListNode slowRunner = firstNode;
LinkedListNode fastRunner = firstNode;

// until we hit the end of the list
while (fastRunner != null && fastRunner.next != null) {
slowRunner = slowRunner.next;
fastRunner = fastRunner.next.next;

// case: fastRunner is about to "lap" slowRunner
if (fastRunner == slowRunner) {
return true;
}
}

// case: fastRunner hit the end of the list
return false;

while循环的条件不应该是fastRunner != null && fastRunner.next.NEXT!= null吗?在目前的代码中,fastRunner可以是链表中的最后一个节点,因此一旦进入while循环,最后一个节点的下一个节点将导致异常。

最佳答案

With the current code, fastRunner can be the very last node in the linked list

fastRunner 不能是链表中的最后一个节点,因为您的 while 循环

while (fastRunner != null && fastRunner.next != null) {

检查fastRunner不是最后一个元素(因为fastRunner.next == null意味着fastRunner是最后一个元素)。您的循环中的此分配

fastRunner = fastRunner.next.next;

当然可以将 fastRunner 设置为 null,但是您没有对它执行任何会导致空指针异常的操作,并且 的下一次迭代while 循环将退出(因为现在 fastRunner == null)

关于java - 链表循环潜在异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45767014/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com