其他分享
首页 > 其他分享> > 优先级队列

优先级队列

作者:互联网



/**
 * @auther: 巨未
 * @DATE: 2019/1/6 0006 10:11
 * @Description: 
           数据结构的队列Queue和集合框架库的队列(小根堆:根节点的值小于左右孩子)不一样
 *         优先级队列!(最前面的优先级最小, 插入按照优先级的高低插入
 */

class PrioQueue{
    class Entry{
        int data;
        int prio; //优先级
        Entry next;

        public Entry(){
            this.data = -1;
            this.prio = -1;
            this.next = null;
        }
        public Entry(int val,int prio) {
            this.data = val;
            this.prio = prio;
            this.next = null;
        }
    }
    private Entry head = null;

     public PrioQueue(){
         this.head = new Entry();
     }
     /*入队*/
    public void pushQueue(int val,int prio){
        if(isFull()){
            return;
        }
        Entry cur = this.head;
        while (cur.next != null) { //遍历一次
            if (cur.next.prio > prio) { //入队的优先级 小于要入队的下一个节点的优先级
                break;
            }
            cur = cur.next;
        }
        Entry entry = new Entry(val,prio);  //入队的节点
        entry.next = cur.next;
        cur.next = entry;
    }
    /*判空*/
    public boolean isEmpty(){
        return this.head.next == null;
    }
    /*判满*/
    public boolean isFull(){
        return this.head == null;
    }
    /*出队*/
    public int popQueue(){
        if(isEmpty()){
            throw new UnsupportedOperationException("is Empty!");
        }
        Entry del = this.head.next;
        int data = del.data;
        this.head.next = del.next;
        return data;
    }
    /*打印*/
    public void show(){
        Entry cur = this.head.next;
        if(isEmpty()){
            System.out.println("队列为空!");
        }
            while(cur != null){
                System.out.print(cur.data+" ");
                cur = cur.next;
        }

            System.out.println();

    }
}
public class TestPrioQueue {

    public static void main(String[] args) {
        PrioQueue prioQueue = new PrioQueue();
        prioQueue.pushQueue(10,9);
        prioQueue.pushQueue(20,4);
        prioQueue.pushQueue(30,5);
        prioQueue.pushQueue(40,0);
        prioQueue.show();  //40  20 30 10
        System.out.println(prioQueue.popQueue());  // 40
        prioQueue.show();// 20 30 10
    }
}

标签:优先级,cur,prio,队列,next,int,Entry,public
来源: https://blog.csdn.net/qq_41384351/article/details/100585337