Pepe Nieto
Pepe Nieto

Reputation: 3

Get maximum value from linked list using recursion, Java

I am trying to get the maximum value using recursion and a 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);
}

However I am getting Java.lang.NullPointerException on the declaration of the int.

Thanks in advance

Upvotes: 0

Views: 1869

Answers (3)

Pepe Nieto
Pepe Nieto

Reputation: 3

I got it to work, thanks to AJB help.

 public static int maxOfMyList(MyListOfInts M){


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


}

Thanks for the help!

Upvotes: 0

Sumit Trehan
Sumit Trehan

Reputation: 4045

The idea here is to pass the linked list node to the recursion tree. Compare the value returned by the child recursive call with current node value and percolate the bigger of the two upwards in the recursion tree. This way you will end up getting the maximum value in the List.

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;
}

Call the above function passing the head of the LinkedList.

Upvotes: 1

Kajal
Kajal

Reputation: 739

Call the function with first element,

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()))
}

Assumptions : next() will point to the next element, value() will return the value of the current element.

Without Math.

 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)
}

Call the function,

maxOfMyList(M,M.value());

Upvotes: 0

Related Questions