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

[LeetCode]Implement Queue using Stacks

时间:2015-11-27 06:45:50      阅读:161      评论:0      收藏:0      [点我收藏+]

标签:

俩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();
    }
}

 

[LeetCode]Implement Queue using Stacks

标签:

原文地址:http://www.cnblogs.com/vision-love-programming/p/4999538.html

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