232. Implement Queue using Stacks

思路: 用2 stack, 當stack1.push的時侯將stack的item放進stack2 中, 當stack1為空時放入item x (item x 在stack1 底部), 再將所有stack2 item放入stack1, --> 即重覆兩次filo --> fifo

class MyQueue {
    Stack stack1;
    Stack stack2;
    

    /** Initialize your data structure here. */
    
    //build a data structure
    public MyQueue() {
        this.stack1 = new Stack<>();
        this.stack2 = new Stack<>();
    }
    
    /** Push element x to the back of queue. */
    public void push(int x) {
        while(!stack1.isEmpty()){
            stack2.push(stack1.pop());
        }
        stack1.push(x);
        while(!stack2.isEmpty()){
            stack1.push(stack2.pop());
        }
    }
    
    /** Removes the element from in front of queue and returns that element. */
    public int pop() {
        return stack1.pop();
    }
    
    /** Get the front element. */
    public int peek() {
        return stack1.peek();
    }
    
    /** Returns whether the queue is empty. */
    public boolean empty() {
        return stack1.isEmpty();
    }
}

你可能感兴趣的:(232. Implement Queue using Stacks)