• 自定义优先级队列PriorityQueue


    搞得简单一点。主要是heapInsert(往堆里面插入数据),heapify(调整堆)这两个函数。

    /**
     * @Author lyuWalle
     * @Date 2020/9/16 11:05
     * @Version 1.0
     * 简单自定义优先级队列,采用ArrayList实现。
     * 主要实现:
     * add(Integer i)
     * peek();
     * poll();
     * size();
     * 
     */
    public class MyPriorityQueue {
        private int cap;
        private List<Integer> list;
        public MyPriorityQueue(){
            this.cap = 10;
            list = new ArrayList<>(10);
        }
        public MyPriorityQueue(int capacity){
            this.cap = capacity;
            list = new ArrayList<>(this.cap);
        }
        public void add(int num){   //将一个新的值插入到大根堆里面
            list.add(num);
            heapInsert(list, list.size() - 1);
        }
    
        private void heapInsert(List<Integer> list, int i) {
            while(list.get(i) > list.get((i - 1)/2)){
                Collections.swap(list, i, (i - 1)/2);
                i = (i - 1)/2;
            }
        }
    
        public void heapify(List<Integer> list, int top, int end){
            int left = top * 2 + 1;
            while(left < end){
                int largest = left + 1 <= end && list.get(left + 1) > list.get(left) ? left + 1 : left;
                if(list.get(largest) > list.get(top)){
                    Collections.swap(list, top, largest);
                }else{
                    break;  //说明不需要调整堆
                }
                top = largest;
                left = 2 * top + 1;
            }
        }
    
        public int peek(){
            if(list.size()>0){
                return list.get(0);
            }else{
                return -1;  //假设队列为空时返回-1
            }
    
        }
        public int poll(){
            if(list.size()>0){
                int top = list.get(0);
                list.remove(0);
                heapify(list, 0, list.size() - 1);
                return top;
            }else{
                return -1;
            }
        }
        public int size(){
            return list.size();
        }
    
        //for test
        public static void main(String[] args) {
            MyPriorityQueue mpq = new MyPriorityQueue();
            mpq.add(1);
            mpq.add(2);
            mpq.add(3);
            mpq.add(4);
            System.out.println(mpq.peek());
            mpq.poll();
            System.out.println(mpq.peek());
            System.out.println(mpq.size());
            mpq.add(5);
            System.out.println(mpq.poll());
            System.out.println(mpq.peek());
        }
    }
  • 相关阅读:
    远程桌面连接win10问题解决
    为什么n各节点的的二叉链表中有n+1个空链域
    西门子Step7找不到有效授权的解决方法
    表达式树获取函数命名
    逆波兰表达式
    双向循环链表实践
    快速找到未知长度单链表的中间节点
    java的ArrayList(线性表)和LinkedList(双向链表)的深入学习
    23种设计模式中的访问者模式
    23种设计模式中的原型模式
  • 原文地址:https://www.cnblogs.com/lyuwalle/p/13678720.html
Copyright © 2020-2023  润新知