数据结构:堆栈

时间:2017-06-20 06:26:55

标签: c stack

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行会发生什么?

1 个答案:

答案 0 :(得分:3)

假设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]