JAVA中的队列实现:
1 // Queue.java 2 // demonstrates queue 3 // to run this program: C>java QueueApp 4 5 class Queue 6 { 7 private int maxSize; 8 private long[] queArray; 9 private int front;10 private int rear;11 private int nItems;12 //--------------------------------------------------------------13 public Queue(int s) // constructor14 {15 maxSize = s;16 queArray = new long[maxSize];17 front = 0;18 rear = -1;19 nItems = 0;20 }21 //--------------------------------------------------------------22 public void insert(long j) // put item at rear of queue23 {24 if(rear == maxSize-1) // deal with wraparound25 rear = -1;26 queArray[++rear] = j; // increment rear and insert27 nItems++; // one more item28 }29 //--------------------------------------------------------------30 public long remove() // take item from front of queue31 {32 long temp = queArray[front++]; // get value and incr front33 if(front == maxSize) // deal with wraparound34 front = 0;35 nItems--; // one less item36 return temp;37 }38 //--------------------------------------------------------------39 public long peekFront() // peek at front of queue40 {41 return queArray[front];42 }43 //--------------------------------------------------------------44 public boolean isEmpty() // true if queue is empty45 {46 return (nItems==0);47 }48 //--------------------------------------------------------------49 public boolean isFull() // true if queue is full50 {51 return (nItems==maxSize);52 }53 //--------------------------------------------------------------54 public int size() // number of items in queue55 {56 return nItems;57 }58 //--------------------------------------------------------------59 } // end class Queue60 61 class QueueApp62 {63 public static void main(String[] args)64 {65 Queue theQueue = new Queue(5); // queue holds 5 items66 67 theQueue.insert(10); // insert 4 items68 theQueue.insert(20);69 theQueue.insert(30);70 theQueue.insert(40);71 72 theQueue.remove(); // remove 3 items73 theQueue.remove(); // (10, 20, 30)74 theQueue.remove();75 76 theQueue.insert(50); // insert 4 more items77 theQueue.insert(60); // (wraps around)78 theQueue.insert(70);79 theQueue.insert(80);80 81 while( !theQueue.isEmpty() ) // remove and display82 { // all items83 long n = theQueue.remove(); // (40, 50, 60, 70, 80)84 System.out.print(n);85 System.out.print(" ");86 }87 System.out.println("");88 } // end main()89 } // end class QueueApp90