【发布时间】:2012-05-31 03:56:02
【问题描述】:
我正在尝试编写迭代器的实现,以便可以调用它 在我的 BST 类中,在 iterator() 方法下。
我的解决方案(不确定它是否能正常工作)是使用堆栈或队列来 存储 BST 的节点。麻烦的是,我的迭代器实现类无法识别我的 当我将“根”节点传递给它的构造函数时的 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;
}
}
这是我为迭代器实现写的
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;
}
}
}
【问题讨论】:
-
“我的迭代器实现类无法识别我的 BST 节点”是什么意思?
-
@Christian,编译器显示一个关于找不到类的错误,我猜它与
DictNode root无关 -
我添加了“作业”标签,因为没有人会重新发明 JDK 中存在的轮子 - 只需使用
TreeSet -
那么问题不在于它不起作用,而是它无法编译?
-
@John B:它没有编译是的,我的意思是它显示了一些与 DictNode 类有关的错误
标签: java data-structures iterator binary-search-tree