Two methods of implementing circular queue in Java array

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.