Java 1.8使用数组实现循环队列
本文实例为大家分享了Java1.8使用数组实现循环队列的具体代码,供大家参考,具体内容如下
1、引入
使用数组实现循环队列,功能如下:
1)isFull():队列满?
2)isEmpty():队列空?
3)add():添加元素。
4)pop():移除元素。
5)display():展示队列。
6)getSize():获取当前队列元素个数。
2、代码
packageDataStructure; importjava.util.Arrays; /** *@author:Inki *@email:inki.yinji@qq.com *@create:20201022 *@last_modify:20201023 */ publicclassMyArrayQueue{ /** *Thedefaultmaxsizeofmyarrayqueue. */ privatefinalintDEFAULT_MAX_SIZE=10; /** *Themaxsizeofmyarrayqueue. */ privateintmaxSize; /** *Thefrontofmyarrayqueue. */ privateintfront; /** *Therearofmyarrayqueue. */ privateintrear; /** *Usingarraytosimulatequeue. */ privateAnyType[]arrQueue; /** *Thefirstconstructor. */ publicMyArrayQueue(){ this(DEFAULT_MAX_SIZE); }//Ofthefirstconstructor /** *Thesecondconstructor. */ publicMyArrayQueue(intparaMaxSize){ maxSize=paraMaxSize+1; arrQueue=(AnyType[])newObject[maxSize]; front=0; rear=0; }//Ofthesecondconstructor /** *Queueisfull? *@return: *Trueiffullelsefalse. */ publicbooleanisFull(){ return(rear+1)%maxSize==front; }//OfisFull /** *Queueisempty? *@return: *Trueifemptyelsefalse. */ publicbooleanisEmpty(){ returnfront==rear; }//OfisEmpty /** *Addelement. *@param: *paraVal: *Thegivenvalue. */ publicvoidadd(AnyTypeparaVal){ if(isFull()){ System.out.println("Thequeueisfull."); return; }//Ofif arrQueue[rear]=paraVal; rear=(rear+1)%maxSize; }//Ofadd /** *Popelement. */ publicAnyTypepop(){ if(isEmpty()){ thrownewRuntimeException("Thequeueisfull."); }//Ofif AnyTyperetVal=arrQueue[front]; front=(front+1)%maxSize; returnretVal; }//ofpop /** *Displayarrayqueue. */ publicvoiddisplay(){ if(isEmpty()){ System.out.println("Thequeueisempty."); return; }//Ofif System.out.print("Thequeueis:["); inti=front; while(i!=(rear+maxSize-1)%maxSize){ System.out.printf("%s,",arrQueue[i]); i=(i+1)%maxSize; }//Ofwhile System.out.printf("%s]",arrQueue[rear-1]); }//Ofdisplay /** *Getcurrentsizeofmyarrayqueue. */ publicintgetSize(){ return(rear-front+maxSize)%maxSize+1; }//OfgetSize /** *Themain **/ publicstaticvoidmain(String[]args){ MyArrayQueue testArrayQueue=newMyArrayQueue<>(3); testArrayQueue.add(1); testArrayQueue.add(2); testArrayQueue.add(4); testArrayQueue.pop(); testArrayQueue.display(); }//Ofmain }//OfMyArrayQueue
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。