[LeetCode]Implement Queue using Stacks

俩stack模拟queue,每次往第一个里面push,要pop的时候pop第二个,如果第二个为空,先把第一个的都放到第二个里面,再pop第二个。平均下来每个数据的时间复杂度为o(1)

class MyQueue {
    // Push element x to the back of queue.
    Stack<Integer> stack1 = new Stack<Integer>();
    Stack<Integer> stack2 = new Stack<Integer>();
    public void push(int x) {
        stack1.push(x);
    }

    // Removes the element from in front of queue.
    public void pop() {
        if (!stack2.isEmpty()) {
            stack2.pop();
        } else {
            while (!stack1.isEmpty()) {
                stack2.push(stack1.pop());
            }
            stack2.pop();
        }
    }

    // Get the front element.
    public int peek() {
        if (!stack2.isEmpty()) {
            return stack2.peek();
        } else {
            while (!stack1.isEmpty()) {
                stack2.push(stack1.pop());
            }
            return stack2.peek();
        }
    }

    // Return whether the queue is empty.
    public boolean empty() {
        return stack1.isEmpty() && stack2.isEmpty();
    }
}

 

posted @ 2015-11-27 05:55  Weizheng_Love_Coding  阅读(133)  评论(0编辑  收藏  举报