Introduction to algorithms ----------- simple implementation of queue

Source: Internet
Author: User

Introduction to algorithms ----------- simple implementation of queue

The basic operations of the queue include enqueue and dequeue. The queue includes head and tail pointers. Elements always exit from the head of the team and enter from the end of the team. When queues are implemented using arrays, the queue space can be used cyclically to make proper use of space.


<喎?http: www.bkjia.com kf ware vc " target="_blank" class="keylink"> VcD4KPHA + PC9wPgo8cHJlIGNsYXNzPQ = "brush: java;"> # include Using namespace std; struct queue {int * q; int queuesize; int head; int tail ;}; void init (queue * q, int n) {q-> head = 0; q-> tail = 0; q-> queuesize = n; q-> q = (int *) malloc (sizeof (int) * q-> queuesize );} void enqueue (queue * q, int x) {if (q-> tail + 1) % q-> queuesize) = q-> head) {cout <"queue is full" <endl;} else {q-> q [q-> tail] = x; q-> tail = (q-> tail + 1) % q-> queuesize;} int dequeue (queue * q, int * value) {if (q-> tail = q-> head) return-1; else {* value = q-> q [q-> head]; q-> head = (q-> head ++) % q-> queuesize) ;}} int main () {int value; queue q; init (& q, 10); for (int I = 0; I <9; I ++) {enqueue (& q, I + 11 );} cout <"head =" <q. head <endl; cout <"tail =" <q. tail <endl; for (int I = 0; I <9; I ++) {if (dequeue (& q, & value) =-1) cout <"queque is empy" <

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.