当前位置:   article > 正文

数据结构和算法(刷题)- 用栈实现队列

数据结构和算法(刷题)- 用栈实现队列

用栈实现队列

  1. 只用1个栈肯定不行,得用两个栈

  2. 思路:一个栈A,一个栈B

    • 入队:栈A入栈,表示入队
    • 出队:栈B有元素就出栈,没有元素就从A中所有元素出栈,都入B栈,再B出栈
  3. 代码:

    public class StackQueue {
    
        private Stack<Integer> stackA = new Stack<Integer>();
        private Stack<Integer> stackB = new Stack<Integer>();
    
        /**
         * 入队操作: 直接入A栈
         * @param element  入队的元素
         */
        public void enQueue(int element) {
            stackA.push(element);
        }
    
        /**
         * 出队操作:若B栈空了,则把A中元素都移入B栈
         */
        public Integer deQueue() {
            if(stackB.isEmpty()){
                if(stackA.isEmpty()){
                    return null;
                }
                transfer();
            }
            return stackB.pop();
        }
    
        /**
         * 栈A元素转移到栈B
         */
        private void transfer(){
            while (!stackA.isEmpty()){
                stackB.push(stackA.pop());
            }
        }
    
        // 测试主代码
        public static void main(String[] args) throws Exception {
            StackQueue stackQueue = new StackQueue();
            stackQueue.enQueue(1);
            stackQueue.enQueue(2);
            stackQueue.enQueue(3);
            System.out.println(stackQueue.deQueue());
            System.out.println(stackQueue.deQueue());
            stackQueue.enQueue(4);
            System.out.println(stackQueue.deQueue());
            System.out.println(stackQueue.deQueue());
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
  4. 思考:入队的时间复杂度显然是 O ( 1 ) O(1) O(1),出队涉及AB两栈的迁移。迁移时时间复杂度为 O ( n ) O(n) O(n),不迁移就是 O ( 1 ) O(1) O(1)。这是均摊时间复杂度,均摊到每次出队上就是 O ( 1 ) O(1) O(1)

声明:本文内容由网友自发贡献,转载请注明出处:【wpsshop博客】
推荐阅读
相关标签
  

闽ICP备14008679号