Java implementation LeetCode 225 achieved by queue stack

Implemented with queue 225. Stack

Queue implementation using the following stack:

push (x) - x elements onto the stack
pop () - remove the top of the stack
top () - Gets the top element
empty () - Returns the stack is empty
Note:

You can only use the basic operation of the queue - that is, push to back, peek / pop from front, size, and is empty of these operations are legal.
The language you are using may not support queue. You can use the list or the deque (deque) to simulate a queue, the queue as long as the operation to the standard.
You may assume that all operations are valid (for example, to an empty stack does not call the pop operation or top).

class MyStack {
  private Queue<Integer> a;//输入队列
    private Queue<Integer> b;//输出队列
    
    public MyStack() {
        a = new LinkedList<>();
        b = new LinkedList<>();
    }
    
    public void push(int x) {
        a.offer(x);
        // 将b队列中元素全部转给a队列
        while(!b.isEmpty())
            a.offer(b.poll());
        // 交换a和b,使得a队列没有在push()的时候始终为空队列
        Queue temp = a;
        a = b;
        b = temp;
    }
    
    public int pop() {
        return b.poll();
    }
   
    public int top() {
        return b.peek();
    }
    
    public boolean empty() {
        return b.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();
 */
Released 1349 original articles · won praise 10000 + · Views 1.2 million +

Guess you like

Origin blog.csdn.net/a1439775520/article/details/104565579