美文网首页
Leetcode 232. Implement Queue us

Leetcode 232. Implement Queue us

作者: bfx1000 | 来源:发表于2020-02-12 15:56 被阅读0次

    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();
        }
    }
    

    相关文章

      网友评论

          本文标题:Leetcode 232. Implement Queue us

          本文链接:https://www.haomeiwen.com/subject/jrlcfhtx.html