美文网首页
17_优先级队列

17_优先级队列

作者: 伶俐ll | 来源:发表于2020-09-10 10:39 被阅读0次

    普通的队列是FIFO原则,也就是先进先出

    优先级队列是按照优先级高低进行出队,比如将优先级最高的元素作为队头优先出队

    优先级队列接口设计

    优先级队列也是一个队列,因此和普通队列提供接口相同

    • int size(){} // 元素的数量
    • boolean isEmpty() {} // 是否为空
    • void enQueue(E element){} // 入队
    • E deQueue(){} // 出队
    • E front(){} // 获取队列头元素
    • void clear(){} // 清空

    优先级队列代码实现

    • 根据优先级队列的特点,很容易想到:可以直接利用二叉堆作为优先级队列的底层实现
    • 可以通过 Comparator 或者 Comparable 去自定义优先级高低
    package PriorityQueue;
    
    import java.util.Comparator;
    
    public class LZPriorityQueue<E> {
    
        private LZBinaryHeap<E> heap;
    
        public LZPriorityQueue(Comparator<E> comparator){
            heap = new LZBinaryHeap<>(comparator);
        }
    
        public LZPriorityQueue(){
            this(null);
        }
    
        /**
         * 入队
         */
        public void enQueue(E element){
            heap.add(element);
        }
    
        /**
         * 出队
         */
        public E deQueue(){
            return heap.remove();
        }
    
        /**
         * 获取队列的头元素
         */
        public E front(){
            return heap.get();
        }
    
        /**
         * 清空
         */
        public void clear(){
            heap.clear();
        }
    
        /**
         * 获取队列的长度
         */
        public int size(){
            return heap.size();
        }
    
        /**
         * 判断队列是否为空
         */
        public boolean isEmpty() {
            return heap.isEmpty();
        }
    
    }
    
    

    相关文章

      网友评论

          本文标题:17_优先级队列

          本文链接:https://www.haomeiwen.com/subject/zoguektx.html