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行会发生什么情况?
发布于 2017-06-20 14:35:14
假设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]https://stackoverflow.com/questions/44645358
复制相似问题