無數據項計數的循環隊列算法:java
在判滿和判空須要注意,因爲是循環隊列,因此有可能rear和front指針指向同一位置,可是出現的狀況有不少,形成可空可滿的狀況,因此數據項要比存儲空間少一,這樣就能解決此問題。算法
又由於沒有數據項技術,因此在統計數據項個數時也應該注意,若是front>rear用maxsize-front+(rear+1),不然用rear-front+1便可。指針
class Queue2 { private int maxSize; private long[] queArray; private int front; private int rear; public Queue2(int s) { maxSize = s+1; queArray = new long[maxSize]; front = 0; rear = -1; } public void insert(long j) { if(rear == maxSize - 1); rear = -1; queArray[++rear] = j; } public long remove() { long temp = queArray[front++]; if(front == maxSize) front = 0; return temp; } public long peekFront() { return queArray[front]; } public boolean isEmpty() { return (rear+1==front||front+maxSize-1==rear); } public boolean isFull() { return (rear+2==front||front+maxSize-2==rear); } public int size() { if(rear >= front) return rear-front+1; else return (maxSize-front)+(rear+1); } } class QueueApp2 { public static void main(String[] args) { Queue2 theQueue = new Queue2(5); theQueue.insert(10); theQueue.insert(11); theQueue.insert(12); theQueue.insert(14); theQueue.remove(); theQueue.remove(); theQueue.remove(); theQueue.insert(77); theQueue.insert(88); theQueue.insert(99); theQueue.insert(77777); while(!theQueue.isEmpty()) { long n = theQueue.remove(); System.out.println(n); System.out.println(" "); } System.out.println(" "); } }
隊列效率:插入,移除速度均爲O(1)。code
雙端隊列:隊列
雙端隊列就是一個兩端都是結尾的隊列。隊列的每一端均可以插入數據項和溢出數據項。這些方法能夠叫作insertLeft()和insertRight(),以及removLeft()和removeRight().rem
若是嚴格禁止調用insertLeft()和removeLeft方法,那麼雙端隊列就是棧。禁用insertLeft()和removeRight(或相反的另外一對方法),它的功能就和隊列同樣了。雙端隊列在容器類庫中有時會提供棧和隊列的功能。it
優先級隊列io
根據關鍵字大小決定數據項在隊列中的位置class
import java.io.IOException; class priorityQ { private int maxSize; private long[] queArray; private int nItems; public priorityQ(int s) { maxSize = s; queArray = new long[maxSize]; nItems = 0; } 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; } queArray[j+1] = item; nItems++; } } public long remove() { return queArray[--nItems]; } public long peekMin() { return queArray[nItems - 1]; } public boolean isEmpty() { return (nItems==0); } public boolean isFull() { return (nItems==maxSize); } } class priorityQApp { public static void main(String[] args) throws IOException { priorityQ thePQ = new priorityQ(5); thePQ.insert(30); thePQ.insert(50); thePQ.insert(10); thePQ.insert(20); thePQ.insert(40); while(!thePQ.isEmpty()) { long item = thePQ.remove(); System.out.println(item + " "); } System.out.println(" "); } }
10 20 30 40 50
優先級效率:效率
插入,刪除都爲O(N)
可是數據項數量大,通常會採用堆