优先级队列:按照优先级存储数据

xiaoxiao2021-02-28  34

优先级队列

代码实现

class PrioLink{ class Entry{ int data; Entry next; int prio; public Entry(){ data = -1; next = null; prio = -1; } public Entry(int data,int prio){ this.data = data; this.prio = prio; this.next = null; } } private Entry head = null; public PrioLink(){ this.head = new Entry(); } /** * 按照优先级进行插入 */ public void insert(int data,int prio){ Entry entry = new Entry(data,prio); Entry cur = this.head; //防止第一个进入的结点 if(cur.next == null){ cur.next = entry; }else{ //插入结点与前面的结点进行优先级的比较 while(cur.next.prio>prio){ cur = cur.next; } //插入 entry.next = cur.next; cur.next = entry; } } /*Entry cur = this.head; for(;cur.next!=null;cur = cur.next){ if(cur.next.prio>prio){ break; } } Entry entry = new Entry(data,prio); entry.next = cur.next; cur.next = entry; }*/ /** * 出队 */ public void pop(){ Entry cur = this.head; if(cur.next == null){ return; } Entry del = cur.next; cur.next = del.next; del = null; } public void show(){ Entry cur = this.head.next; while(cur!=null){ System.out.println(cur.data+" "); cur = cur.next; } System.out.println(); } } public class Test2 { public static void main(String[] args) { // TODO Auto-generated method stub PrioLink p1 = new PrioLink(); p1.insert(10, 1); p1.insert(30, 3); p1.insert(50, 2); p1.show(); p1.pop(); p1.show(); } }

运行结果

转载请注明原文地址: https://www.6miu.com/read-1950297.html

最新回复(0)