public class PriorityQ { private int maxSize; private long[] queArray; private int nItems; //constructor public PriorityQ(int s){ maxSize = s; queArray = new long[maxSize]; nItems = 0; } //insert public void insert(long item){ int j; if(nItems == 0) queArray[nItems++] = item; else{ for(j=nItems-1; j>=0; j--){ if(item > queArray[j]) queArray[j+1] = queArray[j]; else break; }//end for queArray[j+1] = item; nItems++; }//end else } public long remove(){ return queArray[--nItems]; } public long peekMin(){ return queArray[nItems - 1]; } public long peekMax(){ return queArray[0]; } public boolean isEmpty(){ return nItems == 0; } public boolean isFull(){ return nItems == maxSize; } }
public class PriorityQApp { public static void main(String[] args) { PriorityQ thePQ = new PriorityQ(5); thePQ.insert(30); thePQ.insert(50); thePQ.insert(10); thePQ.insert(40); thePQ.insert(20); while(!thePQ.isEmpty()){ System.out.println(thePQ.remove()); } } }
优先级队列
优先级队列是比栈和队列更专用的数据结构。但他在很多情况下都很有用。像普通队列一样,优先级队列有一个队头和一个队尾,并且也是从对头移除数据项。不过在优先级队列中,数据项按关键字的值有序,这样关键字最小数据项(或者在某些实现中是关键字最大的数据项)总在队头。数据项插入的时候会按照顺序插入到合适的位置以确保队列的顺序。