BST クラス内の iterator() メソッドの下で呼び出せるように、反復子の実装を作成しようとしています。
私の解決策 (正しく機能するかどうかはわかりません) は、スタックまたはキューを使用して BST のノードを格納することです。問題は、「ルート」ノードをコンストラクターに渡すと、Iterator 実装クラスが BST ノードを認識できないことです。
想像しやすいように、これは私の BST 実装です。追加、削除などの他のメソッドでも問題なく動作しiterator()
ます。どうやって始めて何をすればいいのかわからないので。
public class DictionaryImp<E extends Comparable<E>> implements Dictionary<E> {
public class DictNode {
public DictNode left;
public DictNode right;
public String position;
public E value;
public DictNode(E value, DictNode left, DictNode right, String position) {
this.left = left;
this.right = right;
this.position = position;
this.value = value;
}
}
public DictNode root;
//... more code
public Iterator<E> iterator() {
// provides a fail fast iterator for the Dictionary
// starting at the least element greater than or equal to start
Iterable<E> itr = new DictionaryItr<E>(root);
Iterator<E> it = itr.iterator();
return it;
}
}
これは私が Iterator 実装のために書いたものです
public class DictionaryItr<E> implements Iterable<E> {
public DictionaryItr(DictNode root) {
first = null;
this.inOrderTraversial(root);
}
public void inOrderTraversial(DictNode node) {
if (node != null) {
inOrderTraversial(node.left);
first.push(node.value);
inOrderTraversial(node.right);
}
}
// more code: push, peek, pop
public Iterator<E> iterator() {
return new ListIterator();
}
private class ListIterator implements Iterator<E> {
private Node current = first;
public boolean hasNext() { return current != null; }
public void remove() { throw new UnsupportedOperationException(); }
public E next() {
if (!hasNext()) throw new NoSuchElementException();
E item = current.item;
current = current.next;
return item;
}
}
}