Your DoubleChainedList
should have a head
and a tail
. Those are the beginning and end of the List respectively. Each node of the list, which you have been instructed to name Elem
, should have a prev
and a next
of type Elem
. Your Elem
class contains another class named Node
- this appears to be superfluous and will likely confuse yourself - flatten this into the Elem
class.
Your smallest()
method contains an error in that it is altering the list. Create a separate Elem
variable to navigate the contents of the list - do not alter head
or tail
here.
It is misleading to return Integer.MIN_VALUE when the list is empty. Consider throwing an Exception if the list is empty instead. You will find that you will have to define special handling for the is-empty case in nearly every method the list implements.
public class DoubleChainedList {
private Elem head;
private Elem tail;
// using protected here because you aren't exposing this to consumers
// but its available for extension
protected class Elem {
private int data;
private Elem prev;
private Elem next;
}
public int smallest() {
if (head == null) {
throw new Exception("list is empty - no smallest value");
}
int min = Integer.MAX_VALUE;
Elem cursor = head;
while (cursor != null) {
min = Math.min(min, cursor.data);
cursor = cursor.next;
}
return min;
}
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…