Queue Array Implementation

Source: Internet
Author: User

For the data structure of each queue, we keep an array theArray and its location front and back, which represent the two ends of the queue. We also need to record the number of elements actually present in the queue

CurrentSize.

To enqueue element x, you can increase currentSize and back by 1 and set theArray [back] = x.

To dequeue an element, you can set the return value to theArray [front], reduce currentSize by 1, and then increase front by 1.

As long as the front or back ends to the end of the array, it will return to the beginning. This is called loop array implementation.
[Cpp] www.2cto.com
# Include <stdio. h>
# Define N 10
 
Int front = 0, back =-1, currentSize = 0;
Void enqueue (int * a, int m)
{
++ Back;
If (front = N)
Front = 0;
If (back = N)
Back = 0;
CurrentSize ++;
A [back] = m;
}
Int dequeue (int *)
{
Return a [front ++];
CurrentSize --;
}
Int main (int argc, char * argv [])
{
Int a [N] = {0 };
Int I;
For (I = 0; I <N; I ++)
Enqueue (a, I );
Enqueue (a, 1 );
// Dequeue ();
 
For (I = 0; I <N; I ++)
Printf ("% 4d", a [I]);
Return 0;
}

Related Article

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.