zoukankan      html  css  js  c++  java
  • 【LeetCode】232. Implement Queue using Stacks

    题目:

    Implement the following operations of a queue using stacks.

    • push(x) -- Push element x to the back of queue.
    • pop() -- Removes the element from in front of queue.
    • peek() -- Get the front element.
    • empty() -- Return whether the queue is empty.

    Notes:

    • You must use only standard operations of a stack -- which means only push to toppeek/pop from topsize, and is empty operations are valid.
    • Depending on your language, stack may not be supported natively. You may simulate a stack by using a list or deque (double-ended queue), as long as you use only standard operations of a stack.
    • You may assume that all operations are valid (for example, no pop or peek operations will be called on an empty queue).

    提示:

    此题要求用“栈”实现“队列”,如果单独用一个栈的话,是不可能的。这里的方法是设置两个栈,具体的思路可以看下面代码的注释。

    代码:

    class Queue {
    private:
        // 设置两个栈
        stack<int> in, out;
    public:
        /** Push element x to the back of queue.
         *  每次push都push到in这个栈当中
         */
        void push(int x) {
            in.push(x);
        }
    
        /** Removes the element from in front of queue.
         *  经过peek操作后,可以保证out的顶部存放的是队列的队首。
         */
        void pop(void) {
            peek();
            out.pop();
        }
    
        /** Get the front element.
         *  先检查一下out是否为空,是的话就把in里面的数据“倒进”out,
         *  这样一来,out的顶部存放的其实是In的底部的数据,也就是最早push进来的数据。
         */
        int peek(void) {
            if (out.empty()) {
                while(in.size()) {
                    out.push(in.top());
                    in.pop();
                }
            }
            return out.top();
        }
    
        /** Return whether the queue is empty.
         *  in和out都空了才算是没有数据了
         */ 
        bool empty(void) {
            return in.empty() && out.empty();
        }
    };
  • 相关阅读:
    【CF1029A】Many Equal Substrings(模拟)
    【CF1028C】Rectangles(线段树)
    【CF1028B】Unnatural Conditions(构造)
    【CF1028A】Find Square(签到)
    【CF1025C】Plasticine zebra(模拟)
    【CF1025A】Doggo Recoloring(签到)
    167.数据传送指令
    166.寻址方式
    165.基础
    164.多媒体操作系统
  • 原文地址:https://www.cnblogs.com/jdneo/p/4775631.html
Copyright © 2011-2022 走看看