2012-01-31 35 views
1

您好我正在做一個鏈表的數據結構,並在列表中定義一個迭代器的內部類。我目前遇到了刪除方法的問題。我想要的功能是,如果下一個未被調用或列表中的當前元素已被刪除,則不能調用它。這是我的。內部迭代器類的問題刪除方法

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,但是我覺得這不是它的方式...

+1

這是功課嗎?如果是,請相應標記。 Java已經有了一個鏈表。 – anubhava 2012-01-31 05:03:27

+0

我沒有意識到有一個單獨的作業標籤,我會牢記未來的作品謝謝! – Erik 2012-01-31 05:34:01

回答

1

如果問題一般來說如何做到這一點,我會看看how Josh Bloch and Neil Gafter做到了。查看Itr的類定義(第330行)。

+2

這適用於AbstractList,它假定有效的基於索引的檢索和刪除。更相關的是http://www.docjar.com/html/api/java/util/LinkedList.java.html LinkedList源文件。 – 2012-01-31 05:28:17

+0

這是一個很好的觀點。 – 2012-01-31 05:29:25

+0

非常感謝你我會這麼做! – Erik 2012-01-31 05:35:37