gpt4 book ai didi

java - java获取链表中的最小元素

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

我正在尝试从链接列表中获取最小元素。然而我的当前代码并没有遍历所有元素,它只检查第一对元素。我知道我的错误在哪里,只是不知道为什么它没有遍历,即使我使用了 next。

    public class ListOfNVersion03PartB
{
private int thisNumber; // the number stored in this node
private ListOfNVersion03PartB next; // forms a linked list of objects

private final int nodeID; // a unique ID for each object in the list

private static int nodeCount = 0; // the number of list objects that have been created


public ListOfNVersion03PartB(int num)
{
thisNumber = num;
next = null;

++nodeCount;
nodeID = nodeCount;

}

public ListOfNVersion03PartB(int [] num)
{
this(num[0]); // in this context, "this" invokes the other constructor

for (int i=1 ; i<num.length ; ++i)
insertLast(num[i]);

}

public int minVal()
{

if(next.thisNumber> thisNumber)
return thisNumber;

else
return next.minVal();

}

最佳答案

因为你没有将next分配给另一个节点,并且它的值为null,所以当你调用minVal()时会抛出NullPointerException

您可以检查 next 是否为 null,如下所示

        public int minVal() {
ListOfNVersion03PartB current = this;
int min = Integer.MAX_VALUE;
while (current != null) {
if (current.thisNumber < min)
min = current.thisNumber;
current = current.next;
}
return min;
}

关于java - java获取链表中的最小元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62268634/

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