简体   繁体   English

使用递归在Java中的双链表中查找最小的元素

[英]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.) 该方法必须返回列表中最小的元素,必须递归,我不能修改方法签名,并且增长函数的O不能大于n(O(nlogn)不可接受。)

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.) (不必担心DoubleLinkedListADT,这是老师提供的接口。可以将DoubleLinkedList引用分配给DoubleLinkedListADT类型,这是它的子级。)

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. 我想我只是不太了解递归,因为我对搜索方法中的第一个return语句不是findSmallest类中返回给搜索调用的返回值感到困惑。 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. 使它适应任何类型的列表应该很容易。

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

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