A queue is a type of data structure that is FIFO, LIFO, and backward
Single queue: Remove elements from the front, insert elements from behind, and be in line with reality
Here we use the pointer to move the position of the method. Because arrays delete elements, if we want to be the same as in the actual queue effect, we need to move the array, it is a waste of time and space.
So:
> When the element is added, when the tail reaches the end of the array, we'll point him to the head.
> When the element is deleted, when the head reaches the end of the array, we reset the head, which points to 0
PackageCom.ghostwu;classQueue {Privateobject[] Queuearr; Private intMaxSize;//Total size Private intFront//Head Private intRear//Tail Private intRealnums;//Queue True Length PublicQueue (int_n) {MaxSize=_n; Queuearr=NewObject[maxsize]; Front= 0; Rear=-1; Realnums= 0; } Public voidAppendintvalue) { if(Isfull ()) {System.out.println ("The queue is full." ); }Else { if(Rear = = maxSize-1) {//The tail is full, point the pointer to the head.Rear =-1; } queuearr[++rear] =value; Realnums++; } } PublicObject Shift () {Object value=NULL; if( !IsEmpty ()) {Value=Peekfront (); Queuearr[front]=NULL; Front++; if(Front = =maxSize) {Front= 0; } realnums--; } returnvalue; } PublicObject Peekfront () {returnQueuearr[front]; } Public BooleanIsfull () {returnRealnums = =maxSize; } Public BooleanIsEmpty () {returnRealnums = = 0; } Public intGetSize () {returnrealnums; } Public voidprint () { for(inti = 0; i < queuearr.length; i++) {System.out.print (Queuearr[i]+ "\ T" ); } }} Public classMyqueue { Public Static voidMain (string[] args) {Queue Q=NewQueue (5 ); Q.append (10 ); Q.append (20 ); Q.append (30 ); Q.append (40 ); Q.append (50 ); System.out.println (Q.peekfront ()); System.out.println (Q.getsize ()); Q.shift (); System.out.println (Q.peekfront ()); Q.print (); Q.append (100 ); Q.append (200 ); }}
Java algorithm-one-way queue