这是我的getSmallest()方法的代码:
public T getSmallest() throws EmptyListException
{
if(isEmpty())
throw new EmptyListException("List is empty");
DLNode<T> current = front;
DLNode<T> minNode = current;
int minimum = current.getValue();
while(current.getNext() != null)
{
if(minimum > current.getValue())
{
minNode = current;
minimum = current.getValue();
}
current = current.getNext();
}
return current.getData();
}
每个节点都有一个名为dataItem的String和一个与之关联的名为value的整数。我想查看哪个节点具有最小值,然后返回dataItem。问题是我陷入了while循环,不知道为什么。如何正确遍历列表,以便我不会陷入while循环并且可以比较最小值?
正如您所见,您不能在Java中重载运算符,而>
只适用于numeric数据类型。
对此的通用解决方案是使用T extends Comparable<T>
并使用其compareTo
方法:
DLNode<T> current = front;
DLNode<T> minNode = current;
T minimum = current.getValue();
while (current.getNext() != null) {
if (minimum.compareTo(current.getValue()) > 0) {
minNode = current;
minimum = current.getValue();
}
current = current.getNext();
}
return current.getData();
(或者,如果T
不是Comparable
,你可以提供一个自定义的Comparator
并以类似的方式使用它)。
问题是:为什么永远不会达到循环终止条件?
作为双向链表,您的列表是否将最后一个元素连接到第一个元素? getNext()
会回答null吗?
此外,写入循环也存在问题。请参阅下面的更正代码。此更新可能无法解决循环终止问题。
public T getSmallest() throws EmptyListException {
if ( isEmpty() ) {
throw new EmptyListException("List is empty");
}
DLNode<T> currentNode = front;
int minValue = currentNode.getValue();
DLNode<T> minNode = currentNode;
while ( (currentNode = currentNode.getNext()) != null ) {
int nextValue = currentNode.getValue();
if ( nextValue < minValue ) {
minNode = currentNode;
minValue = nextValue;
}
}
return minNode.getData();
}