To implement the loop queue method in Java:
1. Add an attribute size to record the current number of elements. The goal is to distinguish the queue as empty or the queue is full when head=rear, by size=0 or size= array length.
2, the array only stores the size of the array-1 elements, to ensure that rear will not be equal to head after a turn, that is, when the queue full, rear+1=head, the middle is just empty an element; When rear=head, it must be the queue empty.
Import java.io.*;p Ublic class Queuearray {object[] A;//object array, the queue stores up to a.length-1 objects int front; Team first subscript int rear; Tail subscript public Queuearray () {this (10);//Call other constructor method} public Queuearray (int size) {a = New Object[size]; Front = 0; Rear = 0; /** * Appends an object to the end of the queue * @param obj Object * @return returns False if the queue is full, otherwise true */public boolean E Nqueue (Object obj) {if ((rear+1)%a.length==front) {return false; } a[rear]=obj; Rear = (rear+1)%a.length; return true; }/** * The first object of the queue header * @return out of the queue object, the queues are empty when NULL is returned */public object Dequeue () {if (rear ==front) {return null; } Object obj = A[front]; Front = (front+1)%a.length; return obj; } public static void Main (string[] args) {Queuearray q = new Queuearray (4);System.out.println (Q.enqueue ("Zhang San")); System.out.println (Q.enqueue ("Reese")); System.out.println (Q.enqueue ("Zhao Wu")); System.out.println (Q.enqueue ("Wang Yi"));//cannot enter queue, queue full for (int i=0;i<4;i++) {System.out.println (q.dequ Eue ()); } } }
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Two methods of implementing circular queue in Java array