【问题标题】:find smallest value in linked list在链表中找到最小值
【发布时间】:2018-05-11 10:58:59
【问题描述】:

无法弄清楚这一点,每次我运行我的代码时,程序都会一直运行下去,链表中的其他所有内容都运行良好。包括删除。

public Node smallestValue() {
    Node current = firstL;
    int min = current.data;

    if (!isEmpty()) {
        while (current != null) {
            if (min < current.data) {
                min = current.data;
                current = current.next;
            }
        }
    } else {
        System.out.println("empty list");
    }

    System.out.println();
    System.out.println(min);

    return current;
}

【问题讨论】:

  • current = current.next移出if声明
  • 而你的情况是错误的。应该是if (min &gt; current.data)

标签: java data-structures linked-list min


【解决方案1】:

无论是否min &lt; current.data,您都需要提前current。只需将作业移到if 之外。 (另外,正如@0x499602D2 在评论中指出的那样,当min 大于 大于current.data 时,要找到需要更改的最小值。)

while(current != null){
    if(min > current.data){
        min = current.data;
    }
    current = current.next;
}

将其作为for 循环执行可能会更简洁:

for (Node current = firstL, int min = current.data;
     current != null;
     current = current.next)
{
    min = Math.min(min, current.data);
}

因为这是在空列表的测试中,所以如果 firstLnull 则不会崩溃(我认为,如果列表不为空,则不会发生这种情况)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-07-30
    • 2011-04-27
    • 1970-01-01
    • 1970-01-01
    • 2018-12-28
    • 1970-01-01
    • 2013-10-31
    • 2012-11-04
    相关资源
    最近更新 更多