zoukankan      html  css  js  c++  java
  • 用栈实现队列

    class Queue {
    private:
        stack<int> in;
        stack<int> out;
        
        void reverseStackToOut()
        {
            auto size = in.size();
            for (size_t i = 0; i < size; ++i){
                out.push(in.top());
                in.pop();
            }
        }
    public:
        // Push element x to the back of queue.
        void push(int x) {
            in.push(x);
        }
        
        // Removes the element from in front of queue.
        void pop(void) {
            if (!out.empty()){
                out.pop();
                return;
            }
            
            if (in.empty()){
                return;
            }
            else{
                reverseStackToOut();
                out.pop();
            }
        }
        
        // Get the front element.
        int peek(void) {
            if (!out.empty()){
                return out.top();
            }
            
            if (in.empty()){
                return 0;
            }
            else{
                reverseStackToOut();
                return out.top();
            }
            
        }
        
        // Return whether the queue is empty.
        bool empty(void) {
            if (in.empty() && out.empty()){
                return true;
            }
            
            return false;
        }
    };
  • 相关阅读:
    04-JQuery
    03-JavaScript
    02-CSS&JS
    01-HTML
    [LeetCode]Insert Interval
    [shell编程]正则表达式
    [LeetCode]Jump Game II
    [LeetCode]Jump Game
    [LeetCode]Wildcard Matching
    [shell编程]初识sed和gawk
  • 原文地址:https://www.cnblogs.com/wuOverflow/p/4700624.html
Copyright © 2011-2022 走看看