232. Implement Queue using Stacks

时间:2020-04-12
本文章向大家介绍232. Implement Queue using Stacks,主要包括232. Implement Queue using Stacks使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

题目链接:https://leetcode.com/problems/implement-queue-using-stacks/

  • 可以用两个栈 inStack,outStack 来实现一个队列
    • inStack 用来接收每次压入的数据,因为需要得到先入先出的结果,所以需要通过一个额外栈 outStack 翻转一次。这个翻转过程(即将 inStack 中的数据压入到 outStack 中)既可以在插入时完成,也可以在取值时完成。
  • 有两点需要注意
    • 如果把 inStack 中的数据压入到 outStack 中,那么必须一次性都压入完
    • 如果 outStack 不为空,那么 inStack 不能向 outStack 中压入数据,换句话说,当 outStack 为空时,再次从 inStack 中压入数据
class MyQueue {
    stack<int> inStack,outStack;
public:
    /** Initialize your data structure here. */
    MyQueue() {
        
    }
    
    /** Push element x to the back of queue. */
    void push(int x) {
        inStack.push(x);
    }
    
    /** Removes the element from in front of queue and returns that element. */
    int pop() {
        in2out();
        int x = outStack.top();
        outStack.pop();
        return x;
    }
    
    /** Get the front element. */
    int peek() {
        in2out();
        return outStack.top();
    }
    
    void in2out(){
        if(outStack.empty()){
            while(!inStack.empty()){
                int x = inStack.top();
                outStack.push(x);
                inStack.pop();
            }
        }
    }
    
    /** Returns whether the queue is empty. */
    bool empty() {
        return inStack.empty() && outStack.empty();
    }
};

原文地址:https://www.cnblogs.com/bky-hbq/p/12686230.html