用两个栈实现队列

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

好像第二种更好一点,毕竟push操作的频率高于pop。

复制代码
 1 class Solution
 2 {
 3 public:
 4     void push(int node) {
 5         if(stack1.empty())
 6             stack1.push(node);
 7         else{
 8             while(!stack1.empty()){
 9                 stack2.push(stack1.top());
10                 stack1.pop();
11             }
12             stack1.push(node);
13             while(!stack2.empty()){
14                 stack1.push(stack2.top());
15                 stack2.pop();
16             }
17         }
18     }
19 
20     int pop() {
21         int t=stack1.top();
22         stack1.pop();
23         return t;
24     }
25 
26 private:
27     stack<int> stack1;
28     stack<int> stack2;
29 };
复制代码
复制代码
 1 class Solution
 2 {
 3 public:
 4     void push(int node) {
 5         stack1.push(node);
 6     }
 7  
 8     int pop() {
 9         int t;
10         while(stack1.size()>1)
11         {
12             stack2.push(stack1.top());
13             stack1.pop();
14         }
15         t = stack1.top();
16         stack1.pop();
17         while(stack2.size()>0)
18         {
19             stack1.push(stack2.top());
20             stack2.pop();
21         }
22         return t;
23     }
24  
25 private:
26     stack<int> stack1;
27     stack<int> stack2;
28 };
复制代码

 

posted @   鸭子船长  阅读(180)  评论(0编辑  收藏  举报
编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
点击右上角即可分享
微信分享提示