Review the next data structure, use the Java array to implement the loop queue.
Classes for queues
1 //Loop Queue2 classcirqueue{3 Private intqueuesize;4 Private intFront;5 Private intRear;6 Private int[] queuelist;7 8 PublicCirqueue (intqueuesize) {9 This. Queuesize =queuesize; TenQueuelist =New int[queuesize]; OneFront = 0; ARear = 0; - } - the //Get Queue Header element - Public intgetqueueelement () { - //if the queue is not empty, return the team header element, otherwise throw an exception prompt queue is empty - intelement =-1; + if(!IsEmpty ()) { -element =Queuelist[front]; + returnelement; A } at Else { -System.out.println ("Queue is empty"); - return-1; - } - - } in - //out Team to Public intDeQueue () { + intelement =-1; - if(!IsEmpty ()) { theelement =Queuelist[front]; *Front = (front+1)%queuesize; $ returnelement;Panax Notoginseng } - Else { theSystem.out.println ("Queue is empty"); + return-1; A } the + } - $ $ - - the //Queue - Public voidEnQueue (intElement) {Wuyi //if the queue is not full, add the element to the tail, otherwise the queue is full the if(!Isfull ()) { -Queuelist[rear] =element; WuRear = (rear+1)%queuesize; - About } $ Else { -System.out.println ("Queue is full"); - } - } A + //determine if the queue is empty the Public BooleanIsEmpty () { - Booleanb =false; $ if(Rear = =front) theb =true; the returnb; the } the - in //determine if the queue is full the Public BooleanIsfull () { the Booleanb =false; About if((rear+1)%queuesize = =front) theb =true; the returnb; the } + -}
Create an object and test
Packagecom.test;ImportJava.util.*; Public classStructtest {/** * @paramargs*/ Public Static voidMain (string[] args) {//TODO auto-generated Method Stub//Create and initialize a circular queue with 3 storage space (easy to determine the condition of the team, wasting an array space)Cirqueue Cirqueue =NewCirqueue (4); //3 Elements of the queueCirqueue.enqueue (1); Cirqueue.enqueue (2); Cirqueue.enqueue (3); //gets the team header element, gets but does not change the queue inttemp =cirqueue.getqueueelement (); SYSTEM.OUT.PRINTLN (temp); //the team gets the team head element and the team head pointer moves backwards onetemp =Cirqueue.dequeue (); SYSTEM.OUT.PRINTLN (temp); //get the team head element againtemp =cirqueue.getqueueelement (); SYSTEM.OUT.PRINTLN (temp); }}
Output:
112
Java uses arrays to implement circular queues