【问题标题】:How to find the minimum element of a doubly linked list in Java如何在Java中找到双向链表的最小元素
【发布时间】:2017-11-12 13:30:13
【问题描述】:

这是我的 getMin() 方法的代码。我无法获得进入while循环的方法。

public E getMin() {

    Node<E> curr = header;
    Node<E> min = curr;
    E temporaryMinimum = header.getElement();
    if (isEmpty()) {
        return curr.getElement();
    }

    while (curr != null) {
        if (curr.getElement() != null) {
            if (temporaryMinimum.compareTo(curr.getElement()) > 0) {
                min = curr;
                temporaryMinimum = curr.getElement();
            }
            curr = curr.getNext();
        }
    }
    return curr.getElement();
}

【问题讨论】:

标签: java doubly-linked-list linear-search


【解决方案1】:

您的 while 循环中似乎存在错误/错字。试试这个(我也改进了一些小方面):

if (isEmpty()) { return null; }

Node<E> curr = header;
Node<E> min  = curr;
E minElement = curr.getElement();

while (curr != null) {
    if (curr.getElement() != null) {
        if (minElement.compareTo(curr.getElement()) > 0) {
            min = curr;
            minElement = curr.getElement();
        }
    }
    curr = curr.getNext();
}
return minElement;

在一般情况下,即使对于双向链表,线性搜索也不会做得更好;)

【讨论】:

    猜你喜欢
    • 2015-01-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-09
    • 1970-01-01
    • 2017-02-25
    相关资源
    最近更新 更多