zoukankan      html  css  js  c++  java
  • 剑指Offer07-两个栈实现队列

    两个栈实现队列的思路:

    队列的特点是的先进先出;

    栈的特点是先进后出;

    将数据存入栈1,再按其输出的特点存入栈2;

    这样数据最后就可以实现先进先出的特点;

    代码实现:

    import java.util.Stack;
    
    public class No7 {
    
        public static void main(String[] args) {
            No7 queue = new No7();
            queue.offer(1);
            queue.offer(2);
            queue.offer(3);
            queue.poll();
            queue.poll();
            queue.poll();
        }
        
        private Stack s1 = new Stack();
        private Stack s2 = new Stack();
        //实现队列的的offer方法:将元素加入到队列的末尾
        public void offer(Object x) {
            s1.push(x);
        }
        
        public void poll() {
            if(s1.size()==0 && s2.size()==0 ) {
                
                try {
                    throw new Exception("队列为空");
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            else {
                if(s2.size()!=0) {
                    System.out.println(s2.peek().toString());
                    s2.pop();
                }
                else {
                    //将s1的数据赋值给s2
                    while(s1.size()>0) {
                        s2.push(s1.pop());
                    }
                    System.out.println(s2.peek().toString());
                    s2.pop();
                }
            }
        }
    
    }
  • 相关阅读:
    vue 组件通信(全)
    clickoutside 代码实现
    reset css 样式重置
    vue computed 无法deep的问题
    sessionStorage的总结
    Windows系统maven安装配置
    Windows系统JDK安装配置
    开篇
    JIT即时编译器
    CLR基础
  • 原文地址:https://www.cnblogs.com/meteorst/p/9222192.html
Copyright © 2011-2022 走看看