我现在编写了一个AVL-tree,并编写了一个迭代器方法,以便按预定顺序遍历整个树。如果我处理'stack.empty()‘这行代码,却不知道为什么,我会得到一个NullPointer。4只眼睛确实比两只眼睛看得更清楚;)。提前感谢您的帮助。
代码:
@Override
public Iterator<E> iterator() {
return new Iterator<E>(){
Node start;
Node current;
// int counter;
Stack<Node> stack;
// int border = count(root);
public void iterator() {
stack = new Stack<Node>();
current = start;
stack.add(root);
}
@Override
public boolean hasNext() {
if(stack.empty()) return false;
else return true;
}
@Override
public E next() {
if(!hasNext()){
throw new NoSuchElementException();
}
Node n = stack.pop();
if(n.left.value != null) stack.push(n.left);
if(n.right.value != null) stack.push(n.right);
return n.value;
}
};
}发布于 2016-01-08 18:26:16
您的意思可能是n.left != null
https://stackoverflow.com/questions/34674609
复制相似问题