[英]Removing a generic type node with the smallest value in a doubly linked list Java
這是我的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的字符串和一個與之關聯的稱為值的整數。 我想查看哪個節點的值最小,然后返回dataItem。 問題是我陷入了while循環中,不知道為什么。 如何正確遍歷列表,以免卡在while循環中並可以比較最小值?
如您所見,您不能在Java中重載運算符,並且>
僅適用於數字數據類型。
通用的解決方案是讓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();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.