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

时间:2015-05-01 20:13:27

标签: java algorithm recursion

我需要类分配来编写具有指定方法签名的方法:

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

该方法必须返回列表中的最小元素,它必须递归,我不能修改方法签名,并且增长函数不能有大于n的大O(O(nlogn)是不可接受的。)

这是我到目前为止所做的:

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

(不要担心DoubleLinkedListADT,它是老师提供的接口。可以将DoubleLinkedList引用分配给DoubleLinkedListADT类型,它是它的子级。)

这适用于空列表,单个元素列表和两个元素列表。任何更大的东西都会失败。我想我只是不理解递归,因为我对搜索方法中的第一个return语句不是返回到findSmallest类中的搜索调用的事实感到困惑。它使用搜索中的最后一个返回调用,它使用第一个最小的对象引用,它是最小的错误。

我没有找人给我正确的代码。我想弄清楚它为什么要这样做。

1 个答案:

答案 0 :(得分:2)

嗯,你的代码很复杂,所有那些双链接爬行看起来很讨厌。 这是最优雅的解决方案,我可以附上一份清单:

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

使其适应任何类型的列表应该很容易。

相关问题