zoukankan      html  css  js  c++  java
  • 225. 用队列实现栈

    传送门

    代码

    class MyStack {
        Queue<Integer> que1;
        Queue<Integer> que2;
        /** Initialize your data structure here. */
        public MyStack() {
            que1 = new LinkedList<>();
            que2 = new LinkedList<>();
        }
        
        /** Push element x onto stack. */
        public void push(int x) {
            que1.offer(x);
        }
        
        /** Removes the element on top of the stack and returns that element. */
        public int pop() {
            int size = que1.size();
            for(int i = 0;i < size - 1; ++i) {
                que2.offer(que1.poll());
            }
            int val = que1.poll();
            while(!que2.isEmpty()) {
                que1.offer(que2.poll());
            }
            return val;
        }
        
        /** Get the top element. */
        public int top() {
            int _top;
            int size = que1.size();
            for(int i = 0;i < size - 1; ++i) {
                que2.offer(que1.poll());
            }
            _top = que1.poll();
            que2.offer(_top);
            while(!que2.isEmpty()) {
                que1.offer(que2.poll());
            }
            return _top;
        }
        
        /** Returns whether the stack is empty. */
        public boolean empty() {
            return que1.isEmpty();
        }
    }
    

    思路

    用两个队列实现一个栈

    (que1) 当主队列,(que2) 当辅助队列

    添加元素都往(que1) 上添加,

    删除元素或者,查看栈顶元素的时候,就把(que1) 全部倒出来,先暂放到 (que2) 中,最后在倒回去(que1) 中即可

  • 相关阅读:
    ContentProvider
    铃声设置
    TTS技术
    http://www.w3cschool.cc/jqueryui/jqueryui-tutorial.html
    HttpHelper
    .net面试题
    函数和原型
    关于递增运算符
    CSS学习笔记
    CSS/CSS3 如何实现元素水平居中
  • 原文地址:https://www.cnblogs.com/lukelmouse/p/14220712.html
Copyright © 2011-2022 走看看