Queue--Array implementation

Source: Internet
Author: User

  You can use arrays to implement a queue by imitating the process of implementing stacks using arrays. Front points to the first element of the team, and the value is always the first element of the array a[0]. When the team is out, the front remains unchanged, the first element is deleted, the remaining elements move forward in turn, and the time complexity is O (n). When the queue is queued, the elements are stored to the appropriate location based on the size of the queues. The above implementation is inefficient because of the constant movement of elements. Therefore, the following uses the form of a ring array to construct the queue. Define two variables:

Front: points to the first element of the team.

Rear: points to the next position in the tail element of the team.
Also set the ring array size to Len. Initial state, front=rear=0. When you queue, the element is stored in the location pointed to by rear, and then rear= (rear+1) is%len. When the team is out, remove the element that front points to, and then make front= (front+1)%len. Finally, Front=rear is both a team full of judgment conditions and team empty judgment conditions, but can be solved perfectly. In the queue method Enqueue, size==capacity, then is the team full. In the out-of-line method, if the size==0, then even if the team is empty. However, this method will cause the original team first element to be overwritten (overwriting the original team first element does not conform to the design intention of the queue), you can prevent the queue size beyond the CAPACITY-1 method to solve this problem. In this way, only the team is empty when the front=rear. Using this method, the "Hot potato" game is realized by using the ring queue. Hot Potato Game rules: A group of children in a circle, between them pass a sweet potato. Among them, a child is responsible for counting, every number of time, the potato to the left neighbor, starting from 1, counting to K when the child with a sweet potato out, and then start again from 1 to say, from the "elimination" of the child's neighbor began to re-pass the potato. The implementation code is as follows:

First, the code for the queue interface is given:

1 /**2 * Created by HFZ on 2016/8/2.3  */4  Public InterfaceQueue {5     voidEnqueue (Object obj);//Queue6Object dequeue ();//out of the team and back to the first element7     intGetSize ();//number of queue elements8     BooleanIsEmpty ();//determine if the queue is empty9Object Front ();//returns to the first elementTen}
View Code

 Then the implementation code:

1 Importjava.util.Objects;2 ImportJava.util.Random;3 4 /**5 * Created by HFZ on 2016/8/2.6  */7 /*8 you can use arrays to implement a queue by imitating the process of implementing stacks using arrays. Front points to the first element of the team, and the value is always the first element of the array a[0]. 9 when the team is out, the front remains unchanged, the first element is deleted, the remaining elements move forward in turn, and the time complexity is O (n). Ten when the queue is queued, the elements are stored to the appropriate location based on the size of the queues.  One  A the above implementation is inefficient because of the constant movement of elements. Therefore, the following uses the form of a ring array to construct the queue.  - define two variables: - Front: points to the first element of the team.  the Rear: points to the next position in the tail element of the team.  - also set the ring array size to Len - initial state, front=rear=0. When you queue, the element is stored in the location pointed to by rear, and then rear= (rear+1) is%len.  - when the team is out, remove the element that front points to, and then make front= (front+1)%len.  + Finally, Front=rear is both a team full of judgment conditions and team empty judgment conditions, but can be solved perfectly. In the queue method Enqueue, - Size==capacity, then the team is full. In the out-of-line method, if the size==0, then even if the team is empty. However, this method will cause the original team first element to be overwritten (overwriting the original team first element + does not conform to the design of the queue), this problem can be resolved by preventing the queue size from exceeding CAPACITY-1. In this way, only the team is empty when the front=rear.  A Various methods of time complexity are O (1) at  */ -  -  Public classQueue_arrayImplementsQueue { -     Private Static intCapacity=40; -     Private intCapacity=0; -     Privateobject[] S; in     Private intFront=0; -     Private intRear=0; to  +      PublicQueue_array (intcapacity) { -          This. capacity=capacity; thes=Newobject[capacity]; *     } $      PublicQueue_array () {Panax Notoginseng          This(capacity); -     } the      Public voidenqueue (Object obj) { +         if(GetSize () ==capacity-1) {//Team Full A             Throw NewExceptionqueuefull ("Team full, can't join"); the         } +         Else{//the team is not full. -             Try { $  $S[rear] =obj; -                 //front= (front+1)%capacity;//the first hand of the team plus 1, and then the length of the array to modulo.  -Rear = (rear + 1)% capacity;//the tail pointer is added 1, then the length of the array is modeled.  the             } -             Catch(ArrayIndexOutOfBoundsException ex) {Wuyi System.out.println (); the             } -         } Wu  -     } About      PublicObject dequeue () { $         if(rear==front) { -             Throw NewExceptionqueueempty ("The team is empty, can't be out of the team"); -         } -         Else{ AObject obj=S[front]; +s[front]=NULL; thefront= (front+1)%capacity; -             returnobj; $         } the     } the  the      PublicObject Front () { the         if(rear==front) { -             Throw NewExceptionqueueempty ("Team empty, no team first element"); in         } the         Else{ the              returnS[front]; About         } the     } the      Public BooleanIsEmpty () { the         if(front==rear) { +             return true; -         } the         Else {Bayi             return false; the         } the     } -      Public intGetSize () { -         return(Capacity+rear-front)%capacity;//rear may be less than front after modulo, cannot be used directly (Rear-front) the     } the  the  the      Public Static voidMain (string[] args) { -String[] children={"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K"}; theQueue_array queue=NewQueue_array (); the //int len=queue.capacity; the         for(String s:children) {94 Queue.enqueue (s); the        } theRandom rand=NewRandom (); the Object dequeueobj;98         intK=rand.nextint (children.length-1) +1; About         //k=4; -          while(Queue.getsize ()!=1){101              for(inti=1;i<k;++i) {102dequeueobj=queue.dequeue ();103 Queue.enqueue (dequeueobj);104             } thedequeueobj=queue.dequeue ();106System.out.println (String.Format ("%s Exit", (String) dequeueobj));107         }108System.out.println (String.Format ("When K was%s winner is%s", K,queue.front ()));109     } the }111  the classExceptionqueueemptyextendsRuntimeException {113      PublicExceptionqueueempty (String err) { the         Super(err); the     } the }117 classExceptionqueuefullextendsruntimeexception{118      PublicExceptionqueuefull (String err) {119         Super(err); -     }121}
View Code

  In fact, in the hot potato game, using the following methods of the queue and the team is better:

In the queue method Enqueue, size==capacity, then is the team full. In the out-of-line method, if size==0, then the team is empty. This method causes the original team's first element to be overwritten, just in accordance with test instructions, and the queue size can be set to the number of children. If you use a method that prohibits queues larger than CAPACITY-1 , the queue size is set to be larger than the number of children, or the queue will be prompted to "full".

Queue--Array implementation

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.