Idiot-maker

  :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

https://leetcode.com/problems/implement-stack-using-queues/

Implement the following operations of a stack using queues.

  • push(x) -- Push element x onto stack.
  • pop() -- Removes the element on top of the stack.
  • top() -- Get the top element.
  • empty() -- Return whether the stack is empty.

Notes:

    • You must use only standard operations of a queue -- which means only push to backpeek/pop from frontsize, and is empty operations are valid.
    • Depending on your language, queue may not be supported natively. You may simulate a queue by using a list or deque (double-ended queue), as long as you use only standard operations of a queue.
    • You may assume that all operations are valid (for example, no pop or top operations will be called on an empty stack).

解题思路:

用了俩queue,思路就很明确了。需要peek或者pop的时候,将一个queue中的元素插入另一个queue,直到只剩一个了,这样才能获得尾端的元素。

也可以只用一个queue,但是在push的时候,就将所有元素立刻反向。

崩溃的是,Queue这个interface,居然没有empty()的方法,连size()的方法都没有。

class MyStack {
    LinkedList<Integer> queue1 = new LinkedList<Integer>();
    LinkedList<Integer> queue2 = new LinkedList<Integer>();
    
    // Push element x onto stack.
    public void push(int x) {
        if(queue1.size() > 0) {
            queue1.offer(x);
        } else {
            queue2.offer(x);
        }
    }

    // Removes the element on top of the stack.
    public void pop() {
        if(queue1.size() == 0) {
            LinkedList<Integer> temp = queue1;
            queue1 = queue2;
            queue2 = temp;
        }
        while(queue1.size() > 1) {
            queue2.offer(queue1.poll());
        }
        queue1.poll();
    }

    // Get the top element.
    public int top() {
        if(queue1.size() == 0){
            LinkedList<Integer> temp = queue1;
            queue1 = queue2;
            queue2 = temp;
        }
        while(queue1.size() > 1) {
            queue2.offer(queue1.poll());
        }
        int res = queue1.peek();
        queue2.offer(queue1.poll());
        return res;
    }

    // Return whether the stack is empty.
    public boolean empty() {
        return queue1.size() == 0 && queue2.size() == 0;
    }
}

 

posted on 2015-06-13 15:09  NickyYe  阅读(237)  评论(0编辑  收藏  举报