LeetCode: 225. Implement Stack using Queues queue implementation Stack

试题
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:

Stack MyStack MyStack = new ();

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

By You the MUST use only Standard the Operations of A Queue - Which means only the Push to the Back, PEEK / POP from Front, size, and IS empty the Operations are! Valid.
DEPENDING ON your Language, Queue May not BE Supported natively by You May Simulate A Queue by. the using A List or the deque (Double-ended Queue), AS Long AS you use only Standard Operations of A Queue.
by you On May the ASSUME that All Operations are Valid (for Example, NO POP or Top Operations Will BE Called ON AN empty Stack).
Code
because the queue of the FIFO principle, we want to get the last element, only the front of the queue element into another, or to re-offer into the queue.

class MyStack {

    Queue<Integer> queue1, queue2;
    int top;
    /** Initialize your data structure here. */
    public MyStack() {
        queue1 = new LinkedList<Integer>();
        queue2 = new LinkedList<Integer>();
    }
    
    /** Push element x onto stack. */
    public void push(int x) {
        queue1.offer(x);
        top = x;
    }
    
    /** Removes the element on top of the stack and returns that element. */
    public int pop() {
        while(queue1.size() > 1){
            top = queue1.poll();
            queue2.offer(top);
        }
        Queue<Integer> temp = queue2;
        queue2 = queue1;
        queue1 = temp;
        return queue2.poll();
    }
    
    /** Get the top element. */
    public int top() {
        return top;
    }
    
    /** Returns whether the stack is empty. */
    public boolean empty() {
        return queue1.isEmpty() && queue2.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();
 */
Published 557 original articles · won praise 500 · Views 1.53 million +

Guess you like

Origin blog.csdn.net/qq_16234613/article/details/100160378