Leetcode 225 Implement Stack using Queues STL

用两个队列去实现栈,这里我使用了队列数组q[2],在所有的过程中保证一个队列是空的

push时插入到空的队列中,然后将队列中的元素移到另一个队列中

pop时从不空的队列中pop()

peek时从不空的队列中取出front()

 1 class Stack {
 2 public:
 3     queue<int> q[2];
 4     
 5     // Push element x onto stack.
 6     void move(int x){
 7         while(!q[1-x].empty()){
 8             q[x].push(q[1-x].front());
 9             q[1-x].pop();
10         }
11     }
12     
13     void push(int x) {
14         for(int i = 0; i < 2; ++i){
15             if(q[i].empty()){
16                 q[i].push(x);
17                 move(i);
18                 break;
19             }
20         }
21     }
22 
23     // Removes the element on top of the stack.
24     void pop() {
25         for(int i = 0; i < 2; ++i){
26             if(!q[i].empty()){
27                 q[i].pop();
28                 break;
29             }
30         }
31     }
32 
33     // Get the top element.
34     int top() {
35         for(int i = 0; i < 2; ++i){
36             if(!q[i].empty()){
37                 return q[i].front();
38             }
39         }
40     }
41 
42     // Return whether the stack is empty.
43     bool empty() {
44         return q[0].empty() && q[1].empty();
45     }
46 };

 

转载于:https://www.cnblogs.com/onlyac/p/5259820.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值