zoukankan      html  css  js  c++  java
  • 如何用两个栈实现队列

    import java.util.Stack;
    
    public class QueueTest {
    
        private Stack<Integer> inStack=new Stack<>();
        private Stack<Integer> outStack=new Stack<>();
        /**
         * 
         * @Description: (入栈) 
         * @author: liyhui
         * @date: 2018年11月24日
         * @param ele
         */
        public void enQueue(int ele ) {
            inStack.push(ele);
        }
        /**
         * 
         * @Description: (出栈) 
         * @author: liyhui
         * @date: 2018年11月24日
         * @param ele
         */
        public Integer deQueue( ) {
            if(outStack.isEmpty()) {
                if(inStack.isEmpty()) {
                    return null;
                }
                this.transfer();
            }
            return outStack.pop();
        }
        /**
         * 
         * @Description: (将入栈的元素给出栈) 
         * @author: liyhui
         * @date: 2018年11月24日
         */
        private void transfer() {
            while(!inStack.isEmpty()) {
                outStack.push(inStack.pop());
            }        
        }
        
        public static void main(String[] args) {
            QueueTest test=new QueueTest();
            test.enQueue(1);
            test.enQueue(2);
            test.enQueue(3);
            
            System.out.println(test.deQueue());
            test.enQueue(4);
            System.out.println(test.deQueue());
            System.out.println(test.deQueue());
            System.out.println(test.deQueue());
        }
    }
  • 相关阅读:
    MyEclipse和Eclipse非常方便的快捷键
    java面试题及答案
    Java笔试题解答
    Spring自定义注解
    Spring MVC上传文件
    JS实现购物车特效
    MySQL软件基本管理
    初识数据库
    Python3-IO模型
    Python3-协程
  • 原文地址:https://www.cnblogs.com/dongma/p/10012275.html
Copyright © 2011-2022 走看看