【Leetcode】225. Implement Stack using Queues

来源:互联网 发布:淘宝洗衣液假货多吗 编辑:程序博客网 时间:2024/06/06 11:46

思路:

用两个队列模拟一个堆栈:队列a和b

(1)取栈顶元素: 返回有元素的队列的首元素

(2)判栈空:若队列a和b均为空则栈空

(3)入栈:a队列当前有元素,b为空(倒过来也一样)则将需要入栈的元素先放b中,然后将a中的元素依次出列并入列倒b中。(保证有一个队列是空的)

(4)出栈:将有元素的队列出列即可。

算法保证在任何时候都有一队列为空。

public class MyStack {    private Queue<Integer> queue1;    private Queue<Integer> queue2;        /** Initialize your data structure here. */    public MyStack() {        queue1 = new LinkedList<Integer>();        queue2 = new LinkedList<Integer>();    }        /** Push element x onto stack. */    public void push(int x) {        if (queue1.isEmpty()) {            queue1.offer(x);            while(!queue2.isEmpty()){                int tmp = queue2.peek();                queue2.poll();                queue1.offer(tmp);            }        }else{            queue2.offer(x);            while(!queue1.isEmpty()){                int tmp = queue1.peek();                queue1.poll();                queue2.offer(tmp);            }        }    }        /** Removes the element on top of the stack and returns that element. */    public int pop() {        if (!queue1.isEmpty())            return queue1.poll();        else            return queue2.poll();    }        /** Get the top element. */    public int top() {        if (!queue1.isEmpty())            return queue1.peek();        else            return queue2.peek();    }        /** Returns whether the stack is empty. */    public boolean empty() {        return queue1.isEmpty() && queue2.isEmpty();     }}/** * Your MyStack object will be instantiated and called as such: * MyStack obj = new MyStack(); * obj.push(x); * int param_2 = obj.pop(); * int param_3 = obj.top(); * boolean param_4 = obj.empty(); */

Runtime:92ms

1 0
原创粉丝点击