首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >数据结构:堆栈

数据结构:堆栈
EN

Stack Overflow用户
提问于 2017-06-20 14:26:55
回答 1查看 70关注 0票数 1
代码语言:javascript
复制
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行时,输出将为

代码语言:javascript
复制
|3|
|2|
|1|

我在理解上面提到的几行代码时遇到了问题。有没有人能解释一下上面这行。第4-8行会发生什么情况?

EN

回答 1

Stack Overflow用户

发布于 2017-06-20 14:35:14

假设pop0是一个拼写错误,并且它应该是对pop()的调用,它将移除您推送到堆栈的最后一个元素并返回该元素。让我们来看看这个程序:

代码语言:javascript
复制
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]
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/44645358

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档