这个问题已经在这里有一个答案:
使用什么和q != null
之间!q.isEmpty()
的区别?
当我用!Q =在下面的代码空,它不会进行编译。但是!q.isEmpty()工作得很好。
java的
Queue<TreeNode[]> q=new LinkedList<>();
q.add(new TreeNode[]{t1, t2});
while(q!=null){ // is not complied
TreeNode[] t=q.remove();
if(t[0]==null || t[1]==null) continue;
t[0].val+=t[1].val;
if(t[0].left==null) t[0].left=t[1].left;
else q.add(new TreeNode[]{t[0].left, t[1].left});
if(t[0].right==null) t[0].right=t[1].right;
else q.add(new TreeNode[]{t[0].right, t[1].right});
}
“Q”永远不会为空,因为你已经有new LinkedList
实例化它所以会导致一个无限循环。所以,在你的榜样,你要检查,如果该列表是空的。但它应该编译