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;
    }
};

四、运行结果

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_44587168/article/details/105849374