232. 用栈实现队列

✔做题思路 or 感想 :

  • 用栈来实现队列的一般方法是:造一个输入栈和一个输出栈来模拟队列
    • 当要push时,则把元素push进输入栈
    • 当要pop时,检测输出栈是否有元素。若有,则直接把输出栈的栈顶元素pop掉就好。若无,则要先把输入栈的元素倒进输出栈,再进行操作
class MyQueue {
public:
    MyQueue() {

    }
    stack<int> InSt;	//先造两个输入,输出栈 
    stack<int> OutSt;
    void push(int x) {
        InSt.push(x);
    }
    
    int pop() {	//若输出栈有元素,则pop,若无,则先把输入栈倒进输出栈
        if (OutSt.size() != 0) {
            int result = OutSt.top();
            OutSt.pop();
            return result;
        } else {
            while (InSt.size() != 0) {
                OutSt.push(InSt.top());
                InSt.pop();
            }
            int result = OutSt.top();
            OutSt.pop();
            return result;
        }
    }
    
    int peek() {
        if (OutSt.size() != 0) {
            int result = OutSt.top();
            return result;
        } else {
            while (InSt.size() != 0) {
                OutSt.push(InSt.top());
                InSt.pop();
            }
            int result = OutSt.top();
            return result;
        }
    }
    
    bool empty() {
        return InSt.empty() && OutSt.empty();   
    }
};

/**
 * Your MyQueue object will be instantiated and called as such:
 * MyQueue* obj = new MyQueue();
 * obj->push(x);
 * int param_2 = obj->pop();
 * int param_3 = obj->peek();
 * bool param_4 = obj->empty();
 */
posted @   北原春希  阅读(32)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
点击右上角即可分享
微信分享提示