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<Integer> stack1;
    Stack<Integer> 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();
    }
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容