简体   繁体   English

如何在Java中找到双向链表的最小元素

[英]How to find the minimum element of a doubly linked list in Java

This is my code for the getMin() method.这是我的 getMin() 方法代码。 I cannot get the method to enter the while loop.我无法获得进入 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();
}

Looks like there is a bug/typo in your while loop.看起来您的 while 循环中存在错误/错别字。 Try this instead (I also improved some minor aspects as well):试试这个(我也改进了一些小方面):

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;

In the general case, you can't do better than a linear search even for doubly-linked lists ;)在一般情况下,即使对于双向链表,您也不能比线性搜索做得更好;)

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

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