用队列实现栈

作者: 飞白非白 | 来源:发表于2018-12-04 23:33 被阅读5次
    
    /**
    Description
    
    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
    
    */
    class MyStack {
        /** Initialize your data structure here. */
        private LinkedList<Integer> q1 = new LinkedList<>();
        public MyStack() {
            q1 = new LinkedList<Integer>();
        }
    
        /** Push element x onto stack. */
        public void push(int x) {
            q1.add(x);
            int size = q1.size();
            while(size > 1){
                q1.add(q1.remove());
                size--;
            }
        }
    
        /** Removes the element on top of the stack and returns that element. */
        public int pop() {
            return q1.remove();
        }
    
        /** Get the top element. */
        public int top() {
            return q1.peek();
        }
    
        /** Returns whether the stack is empty. */
        public boolean empty() {
            return q1.isEmpty();
        }
    }
    
    

    相关文章

      网友评论

        本文标题:用队列实现栈

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