在双向链表中查找最小元素不起作用

Find the minimum element in a doubly linked list not working

我编写了这段代码,用于查找链表中一组数字中的最小值。

public DLNode<T> getMinimum() {
    if (isEmpty()) {
        return null;
    }
    DLNode<T> curr = head;
    DLNode<T> min = curr;
    T temporaryMinimum = head.getElement();
    while (curr.getElement() != null) {
        if ((Integer) temporaryMinimum < (Integer) curr.getElement()) {
            min = curr;
        }
        curr = curr.getNext();
    }
    return min;
}

我正在使用此代码块对其进行测试

public static void getMinElement(){
    int[] data = {2, 3, 5, 1, 6};
    //Add elements to the list from array data
    DoublyLinkedList<Integer> ll = new DoublyLinkedList<>();

    for (int i = 0; i < data.length; i++) {
        ll.AddLast(data[i]);
    }

    System.out.println("Size: " + ll.size);

    System.out.println("Minimum Element is: " + ll.getMinimum());

}

像这样在 main 中调用:

getMinElement();

它没有抛出任何错误,但它似乎进入了无限循环或其他情况(根据我启动它时在我的机器上使用了多少 CPU 来判断)。

我想指出,我的 IDE (IntelliJ IDEA) 没有显示任何错误或不受控制循环或类似内容的警告。 在过去的几天里,我一直在推理它,没有任何运气,现在我没有想法了。

非常感谢任何帮助。

编辑:我的 DLNode Class 是:

class DLNode<T> {
    DLNode<T> Element;
    T data;
    DLNode<T> next;
    DLNode<T> prev;

    DLNode(T data, DLNode<T> next, DLNode<T> prev) {
        this.data = data;
        this.next = next;
        this.prev = prev;
    }

    T getElement() {
        return data;
    }
    public DLNode<T> getPrev() {
        return prev;
    }
    public void setPrev(DLNode<T> prev) {
        this.prev = prev;
    }
    public DLNode<T> getNext() {
        return next;
    }
    public void setNext(DLNode<T> next) {
        this.next = next;
    }
}
  1. 您的循环应该检查是否 curr != null。否则你最终可能会得到 NullPointerException

  2. 你的比较应该反过来(curr.getElement()应该小于temporaryMinimum才能替换它)。

  3. 找到新的最小值后应修改temporaryMinimum

  4. 如果您的 DLNode class 应该是通用的,您不能将 T 转换为 Integer。您可以要求 T extends Comparable<T>,这将允许您使用 compareTo 而不是 ><.

  5. 哦,如果你仍然得到一个无限循环,也许你的链表是循环的(即最后一个节点的 getNext() returns 第一个节点)。如果没有看到您的 DoublyLinkedList class,我无法确定。

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