美文网首页
Leetcode 225. Implement Stack us

Leetcode 225. Implement Stack us

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

    Question: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:
    
    MyStack stack = new MyStack();
    stack.push(1);
    stack.push(2);  
    stack.top();   // returns 2
    stack.pop();   // returns 2
    stack.empty(); // returns false
    

    Answer

    import java.util.LinkedList;
    import java.util.Queue;
    
    class MyStack {
    
        private Queue<Integer> q = new LinkedList<>();
        private Queue<Integer> temp = new LinkedList<>();
        // add element x at queue top 
        void push(int x){
            while(!q.isEmpty()){
                temp.add(q.poll());
            }
            q.add(x);
            while(!temp.isEmpty()){
                q.add(temp.poll());
            }
        }
    
        // remove
        void pop(){
            q.poll();
        }
    
        // retrieve but not remove
        Integer top(){
            return q.peek();
        }
    
        boolean empty(){
            return q.isEmpty();
        }
    }
    
    

    相关文章

      网友评论

          本文标题:Leetcode 225. Implement Stack us

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