牛客网|面试必刷TOP101

这篇博客探讨了如何利用两个栈的特性来模拟队列的操作。通过将元素推入栈1,在弹出元素时先将栈1的内容转移至栈2,然后从栈2顶部取出元素,实现了先进先出的队列功能。这种方法在不需要频繁进行队列操作时能保持较高的效率。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

BM42 用两个栈实现队列_牛客题霸_牛客网 (nowcoder.com)

由于栈是先进后出,队列是先进先出的,所以需要两个栈来倒来倒去

  1. 将数据都push进入 stack1,pop的时候将stack1 中的数据倒入 stack2 中,再将数据pop出来,再把stack2的数据倒入stack1中
class Solution
{
public:
    void push(int node) {
        stack1.push(node);
    }

    int pop() {
        // stack1 导入 stack2
        while(!stack1.empty()){
            stack2.push(stack1.top());
            stack1.pop();
        }
        // 取出数据
        int res = stack2.top();
        stack2.pop();
        // stack2 导入 stack1
        while(!stack2.empty()){
            stack1.push(stack2.top());
            stack2.pop();
        }
        return res;
    }
private:
    stack<int> stack1;
    stack<int> stack2;
};
  1. 不将 stack2 中的数据还原到 stack1 中,由于每次都是从 stack2 的栈顶取数据,所以直到 stack2 为空的时候再将stack1 中的数据导入 stack2
class Solution
{
public:
    void push(int node) {
        stack1.push(node);
    }

    int pop() {
        // stack2 is empty
        if(stack2.empty()){
            // stack1 导入 stack2
            while(!stack1.empty()){
                stack2.push(stack1.top());
                stack1.pop();
            }
        }
        // 取出数据
        int res = stack2.top();
        stack2.pop();
        return res;
    }

private:
    stack<int> stack1;
    stack<int> stack2;
};

未完待续…

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值