java列表不为空,但poll方法返回null
我的方法应该计算集合nodes
中节点的深度,但对于某些树,会调用NullPointerException
,这是因为queue.poll()
返回null。在该方法的描述中,据说queue.poll()
当且仅当队列为空时返回null。这种情况是在while循环中检查的,所以我的问题是,为什么会发生这种错误以及如何修复它
private Map<Tree, Integer> determineDepth(Tree root, Set<Tree> nodes) {
Map<Tree, Integer> depthMap = new HashMap<>();
Map<Tree, Boolean> visited = new HashMap<>();
LinkedList<Tree> queue = new LinkedList<Tree>();
depthMap.put(root, 0);
visited.put(root, true);
queue.add(root);
Tree node;
while (queue.size() != 0) {
node = queue.poll();
int depth = depthMap.get(node);
for (Tree child : node.children()) {
depthMap.put(child, depth + 1);
visited.putIfAbsent(child, false);
if (!visited.get(child)) {
visited.put(child, true);
queue.add(child);
}
}
}
return depthMap;
}
# 1 楼答案
如果将
null
添加到LinkedList,它将被保留。e、 g