I'm writing my own implementation of a doubly linked list as an exercise, but I don't think I fully understand how to utilize the sentinel nodes at the start and end of the list. I would like to ask about using sentinels in the iterator in particular. Here's my iterator (not finished):
private class MyIterator implements Iterator<T> {
private Node current = first;
public boolean hasNext() {
if(current.next.next == null) return false;
else return true;
}
public T next() {
current = current.next;
if(current.next == null) throw new NoSuchElementException();
return current.data;
}
}
What I want to know is if there's any way I can utilize the tail sentinel in the next() and hasNext() methods to avoid null checks. Or is this fine as it is?
Aucun commentaire:
Enregistrer un commentaire