leetcode刷题(225)——用队列实现栈

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.

Example:

MyStack stack = new MyStack();

stack.push(1);
stack.push(2);  
stack.top();   // returns 2
stack.pop();   // returns 2
stack.empty(); // returns false

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

使用两个队列:

哪个队列为空就将新的元素添加到哪个队列,并将另一个队列的元素移动到这个队列。

之前未考虑移动元素,只在pop和top时再移动元素,造成超时

class MyStack {
    private Queue q1 = new LinkedList<>();
    private Queue q2 = new LinkedList<>();

    /** Initialize your data structure here. */
    public MyStack() {
    }
    
    /** Push element x onto stack. */
    public void push(int x) {
        if(q1.isEmpty()){
            q1.add(x);
            while(!q2.isEmpty()){
                q1.add(q2.poll());
            }
        }else{
            q2.add(x);
            while(!q1.isEmpty()){
                q2.add(q1.poll());
            }
        }
    }
    
    /** Removes the element on top of the stack and returns that element. */
    public int pop() {
        if(!q1.isEmpty()) 
            return q1.poll();
        else
            return q2.poll();
    }
    
    /** Get the top element. */
    public int top() {
        return q1.isEmpty()?q2.peek():q1.peek();
    }
    
    /** Returns whether the stack is empty. */
    public boolean empty() {
        return (q1.size()+q2.size())==0;
    }
}

/**
 * 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();
 */

使用一个队列 

class MyStack {

    private Queue queue = new LinkedList<>();

    public void push(int x) {
        queue.add(x);
        for (int i=1; i

 

你可能感兴趣的:(刷题)