繁体   English   中英

使用递归,Java从链表中获取最大值

[英]Get maximum value from linked list using recursion, Java

我正在尝试使用递归和linked list获取最大值

  public static int maxOfMyList(MyListOfInts M){
    int max = M.restOfTheInts.firstInt;
    if(M == null) {
        return max;
    }
    if(M.firstInt > max ) {
        max = M.firstInt;
    }
    return  maxOfMyList(M.restOfTheInts);
}

但是我在int的声明上得到了Java.lang.NullPointerException

提前致谢

这里的想法是将链接列表节点传递给递归树。 将子递归调用返回的值与当前节点值进行比较,并在递归树中向上渗透两个值中较大的一个。 这样,您最终将在列表中获得最大值。

int FindMax (ListNode node)
{
     if (node == null) {
        return -1; /* Can be a big negative number */
    }

    int x = FindMax (node.next());
    int max = (x > node.getKey()) ? (x): (node.getKey());
    return max;
}

通过LinkedList的head调用上述函数。

用第一个元素调用函数,

public static int maxOfMyList(MyListOfInts M){
    if(M==null){
        return Integer.MIN_VALUE;
     }
    //last element
    if( M.next()==null){
        return M.value();//return current value; 
     } 
    return Math.max( M.value(),maxOfMyList(M.next()))
}

假设:next()将指向下一个元素,value()将返回当前元素的值。

没有数学。

 public static int maxOfMyList(MyListOfInts M,int currentMax){
    if(M==null){
        return currentMax;
     }

     currentMax = M.value()>currentMax?M.value():currentMax;
    //last element
    if( M.next()==null){
        return  currentMax;
     } 

    return  maxOfMyList(M.next()),currentMax)
}

调用函数

maxOfMyList(M,M.value());

多亏了AJB的帮助,我才开始工作。

 public static int maxOfMyList(MyListOfInts M){


    if(M.firstInt > M.restOfTheInts.firstInt ) {
         return M.firstInt;
    }else{
        return maxOfMyList(M.restOfTheInts);
    }


}

谢谢您的帮助!

暂无
暂无

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

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