232. Implement Queue using Stacks

本文介绍了一种使用两个栈高效实现队列的方法。通过将新元素压入一个栈并在需要时转移至另一个栈来实现队列的基本操作:push、pop、peek及empty。这种方法避免了频繁的数据迁移,显著提升了性能。

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

这里写图片描述
这里写图片描述

class MyQueue {
public:
    /** Initialize your data structure here. */
    MyQueue() {

    }

    /** Push element x to the back of queue. */
    void push(int x) {    
        stack<int>s2;
        while(!s1.empty()){
            s2.push(s1.top());
            s1.pop();
        }
         s1.push(x);
        while(!s2.empty()){
            s1.push(s2.top());
            s2.pop();
        }
    }

    /** Removes the element from in front of queue and returns that element. */
    int pop() {
        int x=s1.top();
        s1.pop();
        return x;
    }

    /** Get the front element. */
    int peek() {
        return s1.top();
    }

    /** Returns whether the queue is empty. */
    bool empty() {
        return s1.empty();
    }
private:
    stack<int>s1;
};

上面那个解法虽然简单,但是效率不高,因为每次在push的时候,都要翻转两边栈,下面这个方法使用了两个栈_new和_old,其中新进栈的都先缓存在_new中,入股要pop和peek的时候,才将_new中所有元素移到_old中操作,提高了效率。

class MyQueue {
public:
    /** Initialize your data structure here. */
    MyQueue() {

    }

    /** Push element x to the back of queue. */
    void push(int x) {    
        s2.push(x);
    }

    void shiftStack(){
        if(s1.empty()){
            while(!s2.empty()){
            s1.push(s2.top());
            s2.pop();
        }
        }
    }

    /** Removes the element from in front of queue and returns that element. */
    int pop() {
        shiftStack();
        int x=s1.top();
           s1.pop();
        return x;
    }

    /** Get the front element. */
    int peek() {
           shiftStack();
        return s1.top();
    }

    /** Returns whether the queue is empty. */
    bool empty() {
        return s1.empty()&&s2.empty();
    }
private:
    stack<int>s1,s2;
};

深拷贝浅拷贝
c++中参数传递

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值