Java数据结构——优先级队列
class PriorityQueue{ private int maxSize; //队列的长度 private long[] queueArray; //创建队列的数组的引用 private int curNum; //创建当前元素的个数 public PriorityQueue(int s) { //构造函数 this.maxSize = s; queueArray = new long[maxSize]; //创建对象 curNum = 0; //当前的元素的个数是0 } public void insert(long item){ int j; if(curNum == 0){ //输入1个数,就是1个数 queueArray[curNum++] = item; }else{ //左边是rear,右边是front,左边总比右边大 for(j=curNum-1;j>=0;j--){ //当有2个数时,若第2个数比第1个数大,则交换 if(item>queueArray[j]){ //j在-1的时候停止,rear=0,front=curNum-1 queueArray[j+1] = queueArray[j]; // 1 2 -> 1 1 -> 2 1 }else{break;} // 2 1 3 -> 2 1 1 -> 2 2 1 -> 3 2 1 } queueArray[j+1] = item; curNum++; } } public long remove(){ return queueArray[--curNum]; } public long peekFront(){ return queueArray[curNum-1]; } public boolean isEmpty(){ return (curNum==0); } public boolean isFull(){ return (curNum==maxSize); } } public class PriorityQueue_demo { public static void main(String[] args) { // TODO 自动生成的方法存根 PriorityQueue queue_demo = new PriorityQueue(5); queue_demo.insert(30); queue_demo.insert(10); queue_demo.insert(50); queue_demo.insert(40); queue_demo.insert(20); while( !queue_demo.isEmpty()){ long value = queue_demo.remove(); System.out.println(value+"、"); } } }
本文只发表于博客园和tonglin0325的博客,作者:tonglin0325,转载请注明原文链接:https://www.cnblogs.com/tonglin0325/p/5334819.html