【发布时间】:2012-02-08 22:26:59
【问题描述】:
我基于根节点创建了一个简单的参数化树结构。每个节点都拥有一个包含其子注释的数组列表和一个到其父节点的链接。很简单。
现在是我无法解决的问题(在不久的将来):
我想在这棵树上写一个广度优先搜索。我想在(实现的)迭代器接口的帮助下实现这个特性。但我真的无法让它发挥作用: 问题是也可迭代的列表结构。我不知道如何实现 hasNext()、next() 和 remove() 函数:/
你有什么想法吗?
问候
代码:
public class Tree<T> implements Iterator<T>{
private Node<T> root;
/**
* Default constructor.
*/
public Tree() {
super();
}
/**
* Return the root Node of the tree.
* @return the root element.
*/
public Node<T> getRoot() {
return this.root;
}
/**
* Set the root Element for the tree.
* @param Root the root element to set.
*/
public void setRoot(Node<T> Root) {
this.root = Root;
}
...
和
公共类节点{
public List<Node<T>> children;
public Node<T> parent;
public T data;
/**
* Default constructor.
*/
public Node() {
super();
}
/**
* Create a Node<T> with an instance of T.
* @param data an instance of T.
*/
public Node(T nodeData) {
this();
setData(nodeData);
}
/**
* Create a Node<T> with an instance of T.
* @param data an instance of T.
*/
public Node(T nodeData, Node<T> parentNode) {
this();
setData(nodeData);
setParent(parentNode);
}
...
【问题讨论】:
-
树不应该实现
Iterator<T>,它应该实现Iterable<T>。那么迭代器应该是一个单独的类,它的一个实例由Iterable.iterator()方法返回。
标签: java