1.theStack.push(1);
2.theStack.push(2);
3.theStack.push(3);
4.theStack.push(theStack.pop());
5.theStack.push(theStack.pop() +theStack.pop());
6.theStack.push(6);
7.theStack.push(7);
8.theStack.push(theStack.pop() * theStack.pop());

当执行前3行时,输出将是
|3|
|2|
|1|

我对上述几行理解有困难。有人能解释一下上面的内容吗。4-8号线怎么办?

最佳答案

假设pop0是一个输入错误,并且应该是对pop()的调用,那么它将删除您推送到堆栈的最后一个元素并返回它。让我们按照程序进行:

theStack.push(1);
// 1 is pushed to the stack. The stack now contains [1]

theStack.push(2);
// 2 is pushed to the stack. The stack now contains [2, 1]

theStack.push(3);
// 3 is pushed to the stack. The stack now contains [3, 2, 1]

theStack.push(theStack.pop());
// 3 is popped, and then pushed back in, so the stack still contains [3, 2, 1]

theStack.push(theStack.pop() + theStack.pop());
// 3 and 2 are popped, added, and pushed back in, so the stack now contains
// [5, 1]

theStack.push(6);
// 6 is pushed to the stack. The stack now contains [6, 5, 1]

theStack.push(7);
// 7 is pushed to the stack. The stack now contains [7, 6, 5, 1]

theStack.push(theStack.pop() * theStack.pop());
// 7 and 6 are popped, multiplied, and pushed back in, so the stack now contains
// [42, 5, 1]

08-04 20:46