队列实现栈,栈实现队列

  很常见的两道题:
1、用 queue 实现 stack:LeetCode - 225. Implement Stack using Queues
2、用 stack 实现 queue:LeetCode - 232. Implement Queue using Stacks

一、Implement Stack using Queues

  就是用 queue 来模拟 stack,实现 push、top、pop、empty 功能(值得注意的是,STL 里的 pop 都是不返回值的,这里需要返回 top 值),题目保证不会有空的时候出现 top 或者 pop 的调用(STL 里的 queue 和 stack 在遇到这种情况时也只是运行时崩掉)。

1.1、用两个 queue 模拟 stack

  用两个 queue 模拟,很容易理解,就是始终保持一个 queue 是空的,push 就往另一个 queue 里 push,然后 pop 的话就把不是空的 queue 一直往另一个原本是空的 queue 里边放,知道只剩一个元素,然后 pop 这个元素即可。代码很好写,也很常见,就不写了。

1.2、用一个 queue 模拟 stack

  用一个 queue 的话,就是每次 push 一个数之后,把它前边的数,重新 pop 并 push 会 queue 中,这样每次新 push 的数就在 front 了,pop 和 top 就很方便了:

    queue<int> q;
    MyStack() {}
    
    void push(int x) {
        int cnt = q.size();
        q.push(x);
        while(cnt != 0) {
            const int t = q.front();
            q.pop();
            q.push(t);
            --cnt;
        }
    }
    
    int pop() {
        const int res = q.front();
        q.pop();
        return res;
    }
    
    int top() { return q.front(); }
    
    bool empty() { return q.empty(); }
二、Implement Queue using Stacks

  用 stack 模拟 queue,肯定是有两个 stack,用一个做不到。就是一个用来进,一个用来出,如果出的 stack 是空,就把进的转移到出的里边,然后出,push 永远是往进的里边 push:

    stack<int> sin, sout;
    MyQueue() {}
    
    void push(int x) {
        sin.push(x);
    }
    
    int pop() {
        if(sout.empty()) {
            while(!sin.empty()) {
                const int t = sin.top();
                sin.pop();
                sout.push(t);
            }
        }
        const int res = sout.top();
        sout.pop();
        return res;
    }
    
    int peek() {
        if(sout.empty()) {
            while(!sin.empty()) {
                const int t = sin.top();
                sin.pop();
                sout.push(t);
            }
        }
        return sout.top();
    }
    
    bool empty() {
        return sin.empty() && sout.empty();
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值