简体   繁体   中英

Using recursion to find smallest element in double linked list in Java

I am required for a class assignment to write a method with the specified method signature:

 public static <T extends Comparable<T>> T findSmallest(DoubleLinkedListADT<T> list)

The method must return the smallest element in the list, it must recursion, I cannot modify the method signature, and the growth function cannot have a big O greater than n (O(nlogn) isn't acceptable.)

Here is what I have so far:

public static <T extends Comparable<T>> T findSmallest(DoubleLinkedListADT<T> list) {

    if(list.isEmpty()){
        return null;
    }
    ListIterator<T> lit = list.listIterator();
    T smallest = lit.next();

    return search(lit, smallest);
}

private static <T extends Comparable<T>> T search(ListIterator<T> lit, T smallest){

    if(lit.hasNext()){
        if(smallest.compareTo(lit.next())==1){
            smallest =  lit.previous();
            lit.next();
        }
        search(lit, smallest);
    }
    return smallest;
}

(Don't worry about DoubleLinkedListADT, it is an interface the teacher supplied. It is okay to assign a DoubleLinkedList reference to a DoubleLinkedListADT type, it is its child.)

This works for an empty list, a single element list, and a two element list. Anything larger and it fails. I guess I just don't understand recursion that well because I'm baffled by the fact that the first return statement in the search method is not what is returned to the call to search in the findSmallest class. It uses the last return call in search which uses the first smallest object reference which is the wrong smallest.

I'm not looking for someone to just give me code that is correct. I would like to figure out why it's doing what its doing.

Well, your code is complex and all that double-linked crawling looks nasty. Here is most elegant solution i was able come with for list of ints:

public class Test {

    public static Integer min(Iterator<Integer> it) {
        if (it.hasNext()) {
            return Math.min(it.next(), min(it));
        }
        return Integer.MAX_VALUE;
    }

    public static void main(String[] args) {
        System.out.println(min(Arrays.asList(2, 3, 1, 4, 5).iterator()));
    }
}

Adapting it to list of any type should be easy.

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