您好我正在做一個鏈表的數據結構,並在列表中定義一個迭代器的內部類。我目前遇到了刪除方法的問題。我想要的功能是,如果下一個未被調用或列表中的當前元素已被刪除,則不能調用它。這是我的。內部迭代器類的問題刪除方法
private class ListItr implements java.util.Iterator<E>{
private Node<E> currentNode;
private Node<E> nextNode;
private Node<E> previousNode;
public ListItr(List<E> theList){
previousNode = new Node<E>(null);
currentNode = new Node<E>(null);
nextNode = theList.head;
currentNode.setSuccessor(nextNode);
}
public boolean hasNext(){
return nextNode != null;
}
public E next(){
if(nextNode == null)
throw new NoSuchElementException();
previousNode = currentNode;
currentNode = nextNode;
nextNode = nextNode.getSuccessor();
return currentNode.getElement();
}
public void remove(){
if(currentNode == null)
throw new IllegalStateException();
nextNode = currentNode.getSuccessor();
previousNode.setSuccessor(nextNode);
currentNode = null;
size--;
}
}
正如你所看到的,這將成功拼接刪除的節點列表中的周圍,設置當前節點爲null。但是,如果它在第一次未被調用時被調用,那麼當它不需要時它仍然會運行。我可以通過添加一個標誌nextNotCalled,在構造函數中將其設置爲true,然後在下一個被調用時將其設置爲false,但是我覺得這不是它的方式...
這是功課嗎?如果是,請相應標記。 Java已經有了一個鏈表。 – anubhava 2012-01-31 05:03:27
我沒有意識到有一個單獨的作業標籤,我會牢記未來的作品謝謝! – Erik 2012-01-31 05:34:01