Java数据结构与算法笔记——优先级队列

优先级队列介绍

普通的队列是一种先进先出的数据结构,元素在队列尾追加,而从队列头删除。
在优先队列中,元素被赋予优先级。在插入元素时,要按照优先级找到正确的位置并插入。

实现一个简单的优先级队列

数值的大小作为优先级,数值越大优先级越高。
插入:根据元素的大小插入。
取出:取出队头元素。

在这里插入代码片package queue;

public class QueueTest3 {
    public static void main(String[] args) {
        PriorityQueue queue = new PriorityQueue(3);
        queue.insert(1);
        queue.insert(100);
        queue.insert(23);
        queue.insert(25);

//        System.out.println(queue.peek());

        while (!queue.isEmpty()){
            System.out.println(queue.removeHeader());
        }
    }
}


class PriorityQueue{
    private int[] elements;
    private int maxSize;
    private int nElems;

    public PriorityQueue(int size){
        elements = new int[size];
        maxSize = size;
        nElems = 0;
    }

    //插入数据
    public void insert(int data){
        if(nElems==0){//空队列
            elements[nElems++] = data;
        } else if(nElems != maxSize){
            int j = nElems-1;
            while(j>=0 && data>elements[j]){
                //队列从大到小排序,所以从后向前遍历队列,如果队列中的元素比data小,就把元素往后移动
                elements[j+1] = elements[j];
                j--;
            }
            elements[j+1] = data;
            nElems ++;
        }
    }

    //读队尾数据
    public int peek(){
        if(nElems != 0){
            return elements[nElems-1];
        }else{
            return -1; //我们设定-1表示没数据
        }
    }

//    //取出数据,取出队尾的一个元素
//    public int remove(){
//        int removeData = -1;
//        if(nElems != 0){
//            removeData = elements[nElems-1];
//            elements[nElems-1] = -1;//-1表示没有元素
//            nElems--;
//        }
//        return removeData;
//    }

    //取出数据,取出队头的一个元素
    public int removeHeader(){
        int removeData = -1;
        if(nElems != 0){
            removeData = elements[0];
            for(int i=0;i<nElems-1;i++){
                elements[i] = elements[i+1];
            }
            elements[nElems-1] = -1;//-1表示没有元素
            nElems--;
        }
        return removeData;
    }


    //判断是否为空
    public boolean isEmpty(){
        return (nElems == 0);
    }

}
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值