LeetCode-面试题 03.04:化栈为队

一、题目描述

二、解题思路

两个栈来回倒腾即可,有两种倒腾方法

  • 方法一
    • push的时候把主栈内元素全部转移到辅助栈,然后push进元素,再把辅助栈元素pop空,并push回主栈,这样可保证主栈内元素自顶向下符合队列顺序
    • pop的时候直接pop
  • 方法二
    • push的时候直接push,不做调整操作
    • pop的时候把主栈元素转移到辅助栈,pop掉辅助栈栈顶元素,再把辅助栈元素转移回主栈

三、解题代码

只用了方法一。方法二大同小异

class MyQueue {
   
private:
    stack<int> s1, s2;
public:
    /** Initialize your data structure here. */
    MyQueue() {
   
    }
    
    /** Push element x to the back of queue. */
    void push(int x) {
   
        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() {
   
        auto sln = s1.top();
        s1.pop();
        return sln;
    }
    
    /** Get the front element. */
    int peek() {
   
        return s1.top();
    }
    
    /** Returns whether the queu e is empty. */
    bool empty() {
   
        return s1.size() == 0;
    }
};

四、运行结果

全部评论

相关推荐

我要娶个什么名:学长你电脑闹鬼了
点赞 评论 收藏
分享
12-14 11:43
黑龙江大学 Java
用微笑面对困难:确实比较烂,可以这么修改:加上大学的qs排名,然后大学简介要写一些,然后硕士大学加大加粗,科研经历第一句话都写上在复旦大学时,主要负责xxxx,简历左上角把学校logo写上,建议用复旦大学的简历模板
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务