优先队列与队列

   什么是优先队列?它和普通队列有什么区别?普通队列是一种先进先出的数据结构,元素在队尾追加而从队头删除。在优先队列中,元素被赋予优先级,当访问元素时,具有最高优先级的元素最先删除。优先队列具有最高级先出的行为特征。通常采用堆数据结构来实现。
   对于基本的数据类型的包装器类来说,优先队列中元素默认升序排序,但对于自己定义的类来说,需要自己定义比较器。

//自定义比较器,降序排列
static Comparator<Integer> cmp = new Comparator<Integer>() {
    
    
      public int compare(Integer e1, Integer e2) {
    
    
        return e2 - e1;
      }
    };
public static void main(String[] args) {
    
    
        //不用比较器,默认升序排列
        Queue<Integer> q = new PriorityQueue<>();
        q.add(3);
        q.add(2);
        q.add(4);
        while(!q.isEmpty())
        {
    
    
            System.out.print(q.poll()+" ");
        }
        /**
         * 输出结果
         * 2 3 4 
         */
        //使用自定义比较器,降序排列
        Queue<Integer> qq = new PriorityQueue<>(cmp);
        qq.add(3);
        qq.add(2);
        qq.add(4);
        while(!qq.isEmpty())
        {
    
    
            System.out.print(qq.poll()+" ");
        }
        /**
         * 输出结果
         * 4 3 2 
         */
}

猜你喜欢

转载自blog.csdn.net/weixin_51656756/article/details/121364574