232.Implement Queue using Stacks


用栈实现队列的功能。
MyQueue queue = new MyQueue();

queue.push(1);
queue.push(2);
queue.peek(); // returns 1
queue.pop(); // returns 1
queue.empty(); // returns false

思路:
运用2个栈s_tmp,s ,因为栈是后进先出,队列是先进先出,所以,将每一次push的元素 x 都放到栈的栈底,先将栈 s 中的元素依次放入 s_tmp 中,再将 x 放入 s_tmp中,最后将 s_tmp中的元素再放入 s 中,则, 栈 s 中的元素始终都是最先进的在栈顶,最后进的在栈底。

 

class MyQueue {
private:
    stack<int> s_tmp, s;
public:
    void push(int x) {
        while (!s.empty()) {
            s_tmp.push(s.top());
            s.pop();
        }
        s_tmp.push(x);
        while (!s_tmp.empty()) {
            s.push(s_tmp.top());
            s_tmp.pop();
        }
    }
    int pop() {
        int res = s.top();
        s.pop();
        return res;
    }
    int peek() {
        return s.top();
    }
    bool empty() {
        return s.empty();
    }
};

 

 

Java 版:

  • 利用两个栈来做,插入的时候,都插入到 stack2 中;
  • stack2 中,保持存一个元素的大小,超过1个,就放入 stack1 中;
  • 当取队列元素的时候,利用 stack2 中转,拿到 stack1 最底层的元素;
  • 再将 stack2 中转后的元素,放入 stack1 中。

class MyQueue {
    
    /** Initialize your data structure here. */
    Stack<Integer> stack1;
    Stack<Integer> stack2;
    public MyQueue() {
        stack1 = new Stack<>();
        stack2 = new Stack<>();
    }
    
    /** Push element x to the back of queue. */
    public void push(int x) {
        if(stack2.isEmpty()) stack2.push(x);
        else{
            stack1.push(stack2.pop());
            stack2.push(x);
        }
    }
    
    /** Removes the element from in front of queue and returns that element. */
    public int pop() {
        int res;
        while(!stack1.isEmpty()){
            stack2.push(stack1.pop());
        }
        res = stack2.pop();
        while(!stack2.isEmpty()){
            stack1.push(stack2.pop());
        }
        return res;
    }
    
    /** Get the front element. */
    public int peek() {
        int res;
        while(!stack1.isEmpty()){
            stack2.push(stack1.pop());
        }
        res = stack2.peek();
        while(!stack2.isEmpty()){
            stack1.push(stack2.pop());
        } 
        return res;
    }
    
    /** Returns whether the queue is empty. */
    public boolean empty() {
        return stack1.isEmpty() && stack2.isEmpty();
    }
}

 

posted @ 2020-05-12 15:34  星海寻梦233  阅读(83)  评论(0编辑  收藏  举报