【发布时间】:2017-06-24 03:06:51
【问题描述】:
下面只是我代码的一小部分,我试图理解为什么如果我添加注释掉的代码行会引发 EmptyStackException。如果一行中有两个空值(通过调用items.getNextItem() 生成),我需要将oneStack 顶部的项目添加到twoStack 的顶部。对为什么会中断有任何见解吗?或者我如何才能让oneStack 的最高值也成为twoStack 的最高值?
我尝试将那行代码放在if 中,为oneStack.peek() 的值分配一个变量,但这些都没有帮助。几乎就像被注释掉的行正在清空整个堆栈(??)。
要点:如果在注释掉的代码行中我将oneStack.peek() 替换为任何其他值,它就可以正常工作。那么为什么它不适用于oneStack.peek()?
oneStack.push(firstItem);
twoStack.push(firstItem);
nextItem = items.getNextItem();
oneStack.push(nextItem);
twoStack.push(nextItem);
while (!done) {
if (oneStack.peek() == null) {
oneStack.pop();
oneStack.pop();
twoStack.pop();
twoStack.push(oneStack.peek()); // the commented out line below causes this line to throw an EmptyStackException if uncommented.
newItem = items.getNextItem();
oneStack.push(nextItem);
if (oneStack.peek() == null) {
oneStack.pop();
twoStack.pop();
//twoStack.push(oneStack.peek()); // if I uncomment this it breaks, but this needs to happen for twoStack to be correct
} else {
twoStack.push(nextItem);
}
} else if (oneStack.peek() == targetItem) {
done = true;
} else {
nextItem = items.getNextItem();
oneStack.push(nextItem);
twoStack.push(nextItem);
}
这是生成项目的方式:
item1, item2, item3, item4, item5, null, null, item6, item7
最后,这就是堆栈的剩余部分: oneStack: item1, item2, item6, item7
twoStack: item1, item2, item3, item4, item5, item4, item6, item7 (item3 不见了)
twoStack 应该是:item1, item2, item3, item4, item5, item4, item3, item6, item7
【问题讨论】:
-
你从 oneStack 弹出两次然后你在偷看。这个堆栈有多少项?
-
@efekctive 我需要从 oneStack 中弹出两次,以删除空值和它之前的项目以重新开始该项目之前的项目(很抱歉听起来很混乱)。基本上,如果生成了一个空值,它应该从 oneStack 中删除,前一个项目也应该删除,并且之前的项目应该再次添加到 twoStack。
-
好的。但是您确定此时堆栈的大小吗?根据您的代码,它可能为空或不为空。推送前的尺寸是多少?
-
@efekctive 有 6 个项目在栈中命中 null 值时被弹出... null 和前一个项目被弹出,留下 4 个项目,如果它再次通过循环然后又弹出两个,仍然留下两个项目:/
-
异常很明显。循环之前的堆栈大小是多少?经过多少次迭代后异常发生?也许按照弹出的顺序将它们添加到帖子中(null,not null,null)