首页 > 其他 > 详细

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

时间:2020-04-25 18:21:51      阅读:67      评论:0      收藏:0      [点我收藏+]

思路:

  栈——LIFO(后进先出);队列——FIFO(先进先出)。

用两个栈实现队列的根本点是要保证最先进来的(最老的)元素出栈时处于栈顶位置。

使用栈1来入栈,栈2来出栈。具体流程如下:

1. 入栈操作:用栈1入栈,直接push到栈1顶部;(元素全部在栈1,栈2为空)

2. 出栈操作:先将栈1中的元素依次拿出,入栈到栈2中。完成后,原来最先进入栈1的(最老的)元素会在栈2的栈顶,最后进入栈1(最新的)元素会在栈底。

此时,执行栈2的pop,将最老的元素出栈。出栈操作完成。此时,还需要把栈2的元素依次再拿出,push回栈1。

 

 1 class Solution
 2 {
 3 public:
 4     //入栈
 5     void push(int node) {
 6         stack1.push(node);
 7     }
 8     //出栈
 9     int pop() {
10         int top;
11         //将栈1中的内容全部压到栈2中
12         while(!stack1.empty())
13         {
14             stack2.push(stack1.top()); 
15             stack1.pop();
16         }
17         //将栈2的栈顶出栈
18         top=stack2.top();
19         stack2.pop();
20         //将栈2中剩下的内容再放回栈1中
21         while(!stack2.empty())
22         {
23             stack1.push(stack2.top());
24             stack2.pop();
25         }
26         return top;
27     }
28 private:
29     stack<int> stack1;
30     stack<int> stack2;
31 };

 

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

原文:https://www.cnblogs.com/smartheadliu/p/12774119.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!