• 如何用两个栈实现队列


    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());
        }
    }
  • 相关阅读:
    day22-20180522笔记
    day20-20180517笔记
    day19-20180515笔记
    day18-20180513笔记
    day17-20180510笔记
    day16-20180508笔记
    Python之初识面向对象
    Python之常用模块(2)
    Python之常用模块(1)
    Python之模块与包(下)
  • 原文地址:https://www.cnblogs.com/dongma/p/10012275.html
Copyright © 2020-2023  润新知