剑指offer:用两个栈实现队列

浅浅的花香味﹌ 2022-04-14 05:12 364阅读 0赞

题目描述

用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。

思路:

push操作时,push到stack1栈保存

pop操作时,若stack2为空,则把stack1的元素弹出并压入到stack2中,然后弹出stack2中的元素.若stack2不为空,直接弹出栈顶元素.

  1. class Solution
  2. {
  3. public:
  4. void push(int node) {
  5. stack1.push(node);
  6. }
  7. int pop() {
  8. int a;
  9. if(stack2.empty()) {
  10. while(!stack1.empty()) {
  11. a = stack1.top();
  12. stack1.pop();
  13. stack2.push(a);
  14. }
  15. }
  16. a = stack2.top();
  17. stack2.pop();
  18. return a;
  19. }
  20. private:
  21. stack<int> stack1;
  22. stack<int> stack2;
  23. };

发表评论

表情:
评论列表 (有 0 条评论,364人围观)

还没有评论,来说两句吧...

相关阅读