Implement Stack using Queues

来源:互联网 发布:星际淘宝网笔下 编辑:程序博客网 时间:2024/06/07 06:39

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).

Update (2015-06-11):

The class name of the Java function had been updated to MyStack instead of Stack.

思路:用两个queue,q1, q2, q1用来装,然后当要pop的时候,把q1里面所有元素,except最后一个,全部放到q2里面,然后pop最后一个,然后q1,q2交换顺序。所有的费时操作都在pop和top中。

class MyStack {    Queue<Integer> queue1 = new LinkedList<Integer>();    Queue<Integer> queue2 = new LinkedList<Integer>();    // Push element x onto stack.    public void push(int x) {        queue1.add(x);    }    // Removes the element on top of the stack.    public void pop() {        if(queue1.size()!=0){            while(queue1.size()>1){                queue2.add(queue1.poll());            }            queue1.poll();            Queue<Integer> temp = queue1;            queue1 = queue2;            queue2 = temp;        }    }    // Get the top element.    public int top() {        while(queue1.size()>1){            queue2.add(queue1.poll());        }        return queue1.peek();    }    // Return whether the stack is empty.    public boolean empty() {        return (queue1.size()+queue2.size()) == 0;    }}


0 0