zoukankan      html  css  js  c++  java
  • 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();
        }
    };
    
  • 相关阅读:
    js this
    python词云的制作方法
    flask表单标签
    scrapy使用PhantomJS爬取数据
    flask连接sqlalchemy数据库,实现简单的登录跳转功能
    useful tools and website
    sqlalchemy精华版
    flask连接数据库mysql+SQLAlchemy
    flask框架get post方式
    flask基础知识
  • 原文地址:https://www.cnblogs.com/bky-hbq/p/12686230.html
Copyright © 2011-2022 走看看