简体   繁体   中英

Recursive Maximum for a Linked List in Java

To learn recursion and also to write a custom linkedlist (not the LinkedList in java.util ), I tried to create a recursive max() method as follows. I had to struggle a bit, but finally I got it working. However, I am not sure if this is the correct way (or the simplest way). For one thing, I am not quite sure about the base case. I have set the base case to be the last node in the list. Is this the way it should be done? Please advise me on how to write a simple recursive maximum method..

class ListNode{
    int item;
    ListNode next;
}

class RecursiveMax{    

    public static int max(ListNode node,int maxValue){
        //is this the base case ?
        //if last node reached return the current maxValue 
        if(node==null){
            return maxValue;
        }else{
            int v = node.item;
            if(v > maxValue){
                return max(node.next,v);
            }else{
                return max(node.next,maxValue);
            }
        }
    }
    public static void main(String[] args) {
        ListNode a = new ListNode();
        a.item = 11;

        ListNode b = new ListNode();
        b.item = 9;

        ListNode c = new ListNode();
        c.item = 21;

        ListNode d = new ListNode();
        d.item = 17;

        a.next = b;
        b.next = c;
        c.next = d;
        System.out.println("max value in linkedlist="+max(a,0));
    }

}

for the linkedlist abcd (with values 11,9,21,17 ) The output is

max value in linkedlist=21

Well, you are starting your search with 0 as current maximum in main . What happens when all values are negative ?

I think you can do better than that. Call your max method with two parameters private . Then, expose max that only accepts a ListNode .

public static int max(ListNode node) {
    //max value is its value.
    if (node == null) {
        return Integer.MIN_VALUE;
    }
    return max(node, node.item);
}

private static int max(ListNode node,int maxValue){
    int v = node.item;
    if(v > maxValue){
        return max(node.next,v);
    }else{
        return max(node.next,maxValue);
    }
}

Finally, in main , you just call max(a);

Firstly, do not make your class static. darijan's suggestions are good, I prefer throwing exceptions instead of returning any set value, because returning even Interger.MIN_VALUE is ambiguous. You don't know if that's the maximum, or if there are no items in the list.

So I suggest this:

public class linklist {
class ListNode {
    int item;
    ListNode next;
}

ListNode root;

public linklist() {
    this.root = null;
}
    public void add(ListNode node){ /*...*/}
    public int getMax() {
    if (root == null)
        throw new NullPointerException("No items in list");
    return getMaxFrom(this.root, this.root.item);
}

int getMaxFrom(ListNode node, int maxValue) {
    if (node == null)
        return maxValue;
    else {
        return getMaxFrom(node.next, Math.max(node.item, maxValue));
    }
}
}

From a purely technical point of view what you have is fine. The improvement suggested in the first comment is one I would make but that would just improve the readability a little.

Stepping though a list looking for the largest value would be much simpler using interation though. In fact I can't think of a time I've ever recursed though a list. For iteration you can use iterator , for (simple and enhanced), while and do (and probably some others).

If you are looking to learn about recursion I suggest you build a tree structure and work on that. XML is a fine example of a tree structure that will give you exposure to XML processing which you will end up doing some day.

import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

public class RecursionUtils extends Object {

    public static final int findMaxRecursively(List<Integer> numbers) {
        if (numbers.size() > 0) {// terminating condition... if there are no
                                    // elements remaining in the list then
                                    // return 0..
            int num1 = numbers.remove(0); // remove the first element of the
                                            // list, thus in the process we
                                            // truncate the list by one element.
            int num2 = findMaxRecursively(numbers); // find the max from the
                                                    // rest of the list..

            return num1 > num2 ? num1 : num2;
        } else
            return 0;
    }

    public static void main(String[] args) {
        List<Integer> numbers = new LinkedList<>();
        numbers.addAll(Arrays
                .asList(new Integer[] { -1, -2, -3, 0, 6, 5, 3, 2 }));
        System.out.println("The entered list is :");
        System.out.println(numbers);
        System.out.println("\nThe max element is : "
                + findMaxRecursively(numbers));
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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