Leetcode 232. Implement Queue using Stacks

Question:Implement the following operations of a queue using stacks.

push(x) -- Push element x to the back of queue.
pop() -- Removes the element from in front of queue.
peek() -- Get the front element.
empty() -- Return whether the queue is empty.

Example:

MyQueue queue = new MyQueue();

queue.push(1);
queue.push(2);  
queue.peek();  // returns 1
queue.pop();   // returns 1
queue.empty(); // returns false

Answer:

public class MyQueue {

    Stack<Integer> stack = new Stack<Integer>();
    Stack<Integer> tempStack = new Stack<>();

    // put the last-in element to the stack bottom every time.
    void push(int x){
        while(!stack.isEmpty())
            tempStack.push(stack.pop());
        stack.push(x);
        while(!tempStack.isEmpty()){
            stack.push(tempStack.pop());
        }
    }
    // remove
    Integer pop(){
        return stack.pop();
    }

    Integer peek(){
        return stack.peek();
    }

    boolean empty(){
        return stack.isEmpty();
    }
}
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容