zoukankan      html  css  js  c++  java
  • 剑指 Offer 09. 用两个栈实现队列

    传送门

    代码

    class CQueue {
        Stack<Integer> stack1;
        Stack<Integer> stack2;
        public CQueue() {
            stack1 = new Stack<>();
            stack2 = new Stack<>();
        }
        
        public void appendTail(int value) {
            stack1.push(value);
        }
        
        public int deleteHead() {
            while(!stack1.isEmpty()) {
                stack2.push(stack1.pop());
            }
            if(stack2.isEmpty()) return -1;
            int res = stack2.pop();
            while(!stack2.isEmpty()) {
                stack1.push(stack2.pop());
            }
            return res;
        }
    }
    

    思路

    栈只有一个口能进出,而且是 后进先出

    队列需要先进先出,所以我们把 (stack1) 当做主栈,(stack2) 当做辅助栈

    每次都把元素添加到队头,相当于把元素添加到(stack1) 中,

    如果要删除元素的话,就必须把(stack1) 中所有的元素都倒出来放到 (stack2) 中,然后把(stack1) 最底下的那个元素删除,即可

    然后再把元素重新放入(stack1) 中恢复原样

  • 相关阅读:
    数据库ACID
    tcp ip detatils
    process vs thread
    C++ virtual descructor
    static_cast dynamic_cast const_cast reinterpret_cast总结对比
    Meta Programming
    C++ traits
    c++内存管理
    洛谷 P4136 谁能赢呢?
    洛谷 P1166 打保龄球
  • 原文地址:https://www.cnblogs.com/lukelmouse/p/14220679.html
Copyright © 2011-2022 走看看