问题
I have written up this code, to find the minimum of a set of numbers within a linked list.
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;
}
I am testing it using this code block
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());
}
called within main like so:
getMinElement();
It does not throw up any errors, but it seems to go into an infinite loop or something (judging by how much CPU is used on my machine whenever I launch it).
I would like to point out that my IDE (IntelliJ IDEA) does not show any errors or warnings of uncontrolled loops or stuff like that. I've been reasoning about it for the past few days, without any luck, and I'm now out of ideas.
Any help is much appreciated.
EDIT: My DLNode Class is:
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:
Your loop should be checking if
curr != null
. Otherwise you will probably getNullPointerException
eventually.Your comparison should be reversed (
curr.getElement()
should be smaller thantemporaryMinimum
in order to replace it).You should modify
temporaryMinimum
when you find a new minimum.If your
DLNode
class is supposed to be generic, you can't castT
toInteger
. You can require thatT extends Comparable<T>
, which would allow you to usecompareTo
instead of>
or<
.Oh, and if you are still getting an infinite loop, perhaps your linked list is circular (i.e. getNext() of the last node returns the first node). I can't be sure without seeing your
DoublyLinkedList
class.while (curr != null) { if (curr.getElement() != null) { if (temporaryMinimum.compareTo(curr.getElement()) > 0) { min = curr; temporaryMinimum = curr.getElement(); } } curr = curr.getNext(); }
来源:https://stackoverflow.com/questions/47248610/find-the-minimum-element-in-a-doubly-linked-list-not-working