美文网首页
225. 用队列实现栈

225. 用队列实现栈

作者: 上杉丶零 | 来源:发表于2019-02-18 20:50 被阅读0次
    class MyStack {
        private Queue<Integer> queuePush;
        private Queue<Integer> queuePop;
    
        public MyStack() {
            queuePush = new LinkedList<Integer>();
            queuePop = new LinkedList<Integer>();
        }
    
        public void push(int x) {
            queuePush.add(x);
        }
    
        public int pop() {
            int length = queuePush.size();
    
            for (int i = 0; i < length - 1; i++) {
                queuePop.add(queuePush.poll());
            }
    
            int value = queuePush.poll();
            queuePush.addAll(queuePop);
            queuePop.clear();
            return value;
        }
    
        public int top() {
            int length = queuePush.size();
    
            for (int i = 0; i < length - 1; i++) {
                queuePop.add(queuePush.poll());
            }
    
            int value = queuePush.poll();
            queuePop.add(value);
            queuePush.addAll(queuePop);
            queuePop.clear();
            return value;
        }
    
        public boolean empty() {
            return queuePush.isEmpty();
        }
    }
    
    image.png

    相关文章

      网友评论

          本文标题:225. 用队列实现栈

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