码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode 232. Implement Queue using Stacks

时间:2018-08-22 22:54:09      阅读:300      评论:0      收藏:0      [点我收藏+]

标签:pre   push   remove   利用   The   code   rem   call   ram   

方法一:利用两个栈,每次push都利用另一个栈倒一遍。其中push O(n)

class MyQueue {
private:
    stack<int> s1; //the same order of queue
    stack<int> s2;
public:
    /** Initialize your data structure here. */
    MyQueue() {

    }
    
    /** Push element x to the back of queue. */
    void push(int x) {
        while (!s1.empty()){
            int tmp=s1.top(); s1.pop();
            s2.push(tmp);
        }
        s2.push(x);
        while (!s2.empty()){
            int tmp=s2.top(); s2.pop();
            s1.push(tmp);
        }
    }
    
    /** Removes the element from in front of queue and returns that element. */
    int pop() {
        int tmp=s1.top(); s1.pop();
        return tmp;
    }
    
    /** Get the front element. */
    int peek() {
        return s1.top();
    }
    
    /** Returns whether the queue is empty. */
    bool empty() {
        return s1.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();
 */

 

方法二:同样是利用两个栈,但是不同于上一种方法每次push都要倒一次。两个栈记作in和out,out顺序与queue一致。每次push都放到in中,需要pop的时候才把in倒到out中执行。相当于in作为一个缓存,out没元素了才将in中的元素倒入out中。push-O(1); pop-Amortized O(1)。

详见 https://leetcode.com/problems/implement-queue-using-stacks/solution/

class MyQueue {
private:
    stack<int> in;
    stack<int> out;
    int front;
public:
    /** Initialize your data structure here. */
    MyQueue() {

    }
    
    /** Push element x to the back of queue. */
    void push(int x) {
        if (in.empty()) front=x;
        in.push(x);
    }
    
    /** Removes the element from in front of queue and returns that element. */
    int pop() {
        if (out.empty()){ //move from in to out
            while (!in.empty()){
                out.push(in.top()); in.pop();
            }
        }
        int tmp=out.top(); out.pop();
        return tmp;
    }
    
    /** Get the front element. */
    int peek() {
        if (!out.empty()) return out.top();
        else return front;
    }
    
    /** Returns whether the queue is empty. */
    bool empty() {
        return in.empty() && out.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();
 */

 

LeetCode 232. Implement Queue using Stacks

标签:pre   push   remove   利用   The   code   rem   call   ram   

原文地址:https://www.cnblogs.com/hankunyan/p/9520766.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!