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

    简介

    使用队列实现队列哈哈.

    code

    class MyQueue {
    public:
        queue<int> q;
    public:
        /** Initialize your data structure here. */
        MyQueue() {
            
        }
        
        /** Push element x to the back of queue. */
        void push(int x) {
            return q.push(x);
        }
        
        /** Removes the element from in front of queue and returns that element. */
        int pop() {
            int a = q.front();
            q.pop();
            return a;
        }
        
        /** Get the front element. */
        int peek() {
            return q.front();
        }
        
        /** Returns whether the queue is empty. */
        bool empty() {
            return q.empty();
        }
    };
    
    /**
     * Your MyQueue object will be instantiated and called as such:
     * MyQueue* obj = new MyQueue();
     * obj->push(x);
     * int param_2 = obj->pop();
     * int param_3 = obj->peek();
     * bool param_4 = obj->empty();
     */
    
    class MyQueue {
        Stack<Integer> stacka;
        Stack<Integer> stackb;
        /** Initialize your data structure here. */
        public MyQueue() {
            stacka = new Stack<>();
            stackb = new Stack<>();
        }
        
        /** Push element x to the back of queue. */
        public void push(int x) {
            stacka.push(x);
        }
        
        /** Removes the element from in front of queue and returns that element. */
        public int pop() {
            if(stackb.isEmpty()){
                while(!stacka.isEmpty()) {
                    stackb.push(stacka.pop());
                }
            }
            return stackb.pop();
        }
        
        /** Get the front element. */
        public int peek() {
            if(stackb.isEmpty()){
                while(!stacka.isEmpty()){
                    stackb.push(stacka.pop());
                }
            }
            return stackb.peek();
        }
        
        /** Returns whether the queue is empty. */
        public boolean empty() {
            return stackb.isEmpty() && stacka.isEmpty();
        }
    }
    
    /**
     * Your MyQueue object will be instantiated and called as such:
     * MyQueue obj = new MyQueue();
     * obj.push(x);
     * int param_2 = obj.pop();
     * int param_3 = obj.peek();
     * boolean param_4 = obj.empty();
     */
    
    Hope is a good thing,maybe the best of things,and no good thing ever dies.----------- Andy Dufresne
  • 相关阅读:
    E小press框架之第三步(参数接收)
    Express框架之第二步(路由)
    Express框架之第一步(创建工程)
    【排序】基数排序
    【数学】平方和公式$$sum_{i=1}^{n}i^2=frac{n(n+1)(2n+1)}{6}$$
    【博弈论】Nim游戏
    【搜索】对抗搜索【CF】J. Situation
    【图论】Kruskal算法
    dijkstra算法+堆优化 + 链式前向星版本
    【DP】【数位DP】
  • 原文地址:https://www.cnblogs.com/eat-too-much/p/14775035.html
Copyright © 2011-2022 走看看