LeetCode 225. Implement Stack using Queues

来源:互联网 发布:js登录界面 编辑:程序博客网 时间:2024/05/16 19:47
class MyStack {    Queue<Integer> q1 = new LinkedList<Integer>();Queue<Integer> q2 = new LinkedList<Integer>();// Push element x onto stack.    public void push(int x) {    if (q1.isEmpty()) {    q1.offer(x);        while (!q2.isEmpty()) q1.offer(q2.poll());    } else {    q2.offer(x);        while (!q1.isEmpty()) q2.offer(q1.poll());    }    }    // Removes the element on top of the stack.    public void pop() {    if (q1.isEmpty()) q2.poll();    else q1.poll();    }    // Get the top element.    public int top() {    if (q1.isEmpty()) return q2.peek();    else return q1.peek();    }    // Return whether the stack is empty.    public boolean empty() {    return q1.isEmpty() && q2.isEmpty();    }}

0 0