Queue in Java

Source: Internet
Author: User

Defined

The operation of the team is done at both ends, one end can only insert operations (queue), called the tail, one end can only delete operations (out of the team), called the tail of the team.

The queue's operational rules are (first in first FIFO out).

Queue, out-of-team operations have the team and the team's hands, usually in F (front) for the first hand, R (rear) represents the tail of the team pointer.

The storage of a queue has two methods: sequential storage and chained storage.

Basic operations:

    • Initialization
    • Judgment null;
    • Judge full;
    • Team
    • Out of the team;
    • Remove the first element of the team.
Package com.wuwii.test;/*** Queue * @authorZhang Kai * @version1.0* @since <PRE>2017/12/17 13:12</pre> */ Public Interfacequeue<e> {/*** Queue     * @param elementQueued Elements     */    void Enqueue(E Element);/*** First element of the team     * @returnfirst element     */Edequeue();/*** Return to the first element of the team     * @returnE Team first element     */EFrontvalue();/*** Empty all elements of the queue     */    void Clear();/*** Determine if the queue is empty     * @returntrue is empty,     */BooleanIsEmpty();}
Sequential queue

。 Because the space of the sequential storage structure is contiguous, a vector space is required to store all the elements of the current queue, because the position of the queue's head and tail is changed. At initialization time, both rear and front are set to 0, when the new element is inserted into the position referred to by the rear, then the rear is added 1; When the queue is dropped, the element that front refers to is deleted, and then front is added 1 and returned to the element. This shows that the queue is empty when the head-end pointer is equal. In a non-empty queue, the head pointer always points to the team head element, and the tail pointer always points to the next position of the tail element.

There is actually a problem that needs to be solved. The sequential storage structure of queues also has an overflow and underflow problem. Also, there are phenomena in the queue, that is, the 假溢出 queue in the team and out of the operation, the tail and the pointer is constantly increasing without decreasing or only reduce, not increase, resulting in the space of the deleted elements can not be re-use, so, although the actual number of elements in the queue is much smaller than the size of the vector space, However, it is also possible that the tail pointer is far beyond the upper bounds of the vector space and cannot be queued or out of the queue, a phenomenon called false overflow.

There are several ways to resolve false overflows.

    • Fixed head pointer: Fixed team first pointer, once delete element, need to move all elements, and then modify the tail pointer, so that you can insert elements, only when the element is not inserted, the queue is full, otherwise you can always insert elements, but there is a, each time you delete the element, you move a lot of data, Cause performance loss;
    • Loop vector: The queue stored in the loop vector becomes the loop queue.
Loop queue

Queues stored in loop vectors become circular queues

Assuming that the space of the vector is M, as long as the team first and the end of the team at the time of the team to do a modulo operation of M to achieve the team head and tail of the loop, so the team head and tail pointer value range of 0 ~ m-1.

At the time of the queue: rear = (rear + 1) % maxSize ;
When the team is out: front = (front + 1) % maxSize ;

When the team, rear pointer constantly add one, know that the rear pointer when the front pointer, the queue full, rear = front, out of the queue, only need to judge Front = rear. Therefore, there is a problem that the queue is empty and full conditions are the same.

To differentiate between empty and full queues:

    • Way one: a waste of space; rear points to the position just inserted, front points to the position just inserted; When the team first does not modify the rear pointer, first to Judge (rear + 1) % maxSize = front , set up, indicating that the queue is full. When you are out of the team, you only need to judge Front = rear, not empty, delete front = (front + 1) % maxSize the element of the position.
    • Mode two: Set a variable to save the number of stored elements, the variable is compared to the maximum capacity of the queue, if equal, the queue is full, if the variable is 0, indicating that the queue is empty.

Both of these methods require a storage unit to be consumed.

Implementing a circular queue requires the overhead of two pointers, which requires defining the maximum subscript range for the array, followed by the FIFO principle.

Package com.wuwii.test;/*** Sequential Queue-"loop queue" * @authorZhang Kai * @version1.0* @since <PRE>2017/12/17 13:17</pre> */ Public classSqueue<e>Implementsqueue<e> {/*** Queue Default size     */    Private Final intDefaultSize =Ten;/*** Number of elements stored in the queue     */    Private intSize/*** Team First position     */    Private intFront/*** Team Tail position     */    Private intRear/*** Storage Array     */    PrivateObject[] elements;/*** Non-parametric construction, using the default size of ten     */     Public Squeue() {Initqueue(defaultsize); }/*** parameter construction, specifying queue size     * @param givensizeneed to specify queue size     */     Public Squeue(intGivensize) {Initqueue(givensize); }/*** Queue     *     * @param elementQueued Elements     */    @Override     Public void Enqueue(E Element) {Checkfull(); Rear = (rear +1)% size;    Elements[rear] = element; }/*** First element of the team     *     * @returnfirst element     */    @Override     PublicEdequeue() {Checkempty(); Front = (front +1)% size;return(E) Elements[front]; }/*** Return to the first element of the team     *     * @returnE Team first element     */    @Override     PublicEFrontvalue() {return(E) elements[(front +1)% size]; }/*** Empty all elements of the queue     */    @Override     Public void Clear() {if(IsEmpty()) {return; } front = rear =0; }/*** Determine if the queue is empty     *     * @returntrue is empty,     */    @Override     PublicBooleanIsEmpty() {returnFront = = Rear; }/*** Initialize Queue     * @param givensizegiven size     */    Private void Initqueue(intgivensize) {size = Givensize +1; Front = Rear =0; elements =NewObject[size]; }/*** Check queue full* The queue is full and throws an exception     */    Private void Checkfull() {if(Front = = (Rear +1)% size) {Throw NewRuntimeException ("Queue is full"); }    }/*** Check queue is empty* Throws an exception for null     */    Private void Checkempty() {if(IsEmpty()) {Throw NewRuntimeException ("Queue is empty"); }    }}
Chained queues

In comparison to the sequential queue, the first and the end of the chain queue are changed to pointers.

Chain queue exists a very convenient feature, only need a team tail pointer can complete all the basic operations of the queue, the main reason is that the queue operation mode when the first-out, known as an arbitrary node, you can find out all, so only need a team tail can be, save space overhead.

Emptying the queue simply removes the pointer.

Package com.wuwii.test;/*** Chain queue, loop queue * @authorZhang Kai * @version1.0* @since <PRE>2017/12/17 14:14</pre> */ Public classLinkqueue<e>Implementsqueue<e> {/*** Team First hands     */    PrivateNode<e> Front;/*** Team Tail hands     */    PrivateNode<e> Rear; Public Linkqueue() {Initqueue(); }/*** Queue     *     * @param elementQueued Elements     */    @Override     Public void Enqueue(E Element) {if(Rear = =NULL) {rear =NewNode<> (NULL, Element); }Else{Front = rear =NewNode<> (NULL, Element); }    }/*** First element of the team     *     * @returnfirst element     */    @Override     PublicEdequeue() {Checkempty(); E e = front.element; Front = front.Next;returnE }/*** Return to the first element of the team     *     * @returnE Team first element     */    @Override     PublicEFrontvalue() {returnFront.element; }/*** Empty all elements of the queue     */    @Override     Public void Clear() {front = rear =NULL; }/*** Determine if the queue is empty     *     * @returntrue is empty,     */    @Override     PublicBooleanIsEmpty() {returnRear = =NULL; }/*** storage unit, linked list unit     * @param <E>     */    Private Static classnode<e> {node<e> Next;        E element; Node (node<e> Next, E Element) { This.Next= Next; This.element= element; }    }/*** Initialize Queue     */    Private void Initqueue() {front = rear =NULL; }/*** Check queue is empty* Throws an exception for null     */    Private void Checkempty() {if(IsEmpty()) {Throw NewRuntimeException ("Queue is empty"); }    }}

Queue in Java

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.