Queue and Loop queue

Source: Internet
Author: User

Review the implementation of the queue and loop queue (C language)

1, single chain queue:

1typedefstructqnode{//If you do not write a typedef, each time you define Qnode in C you need to precede the struct, and C + + does not have to2 qelemtype data;3     structQnode *Next;4}qnode,*queueptr;5 6typedefstruct{//If you do not write a struct name, you need to add a typedef7 queueptr Front;8 queueptr Rear;9 }linkqueue;Ten  OneStatus Initqueue (Linkqueue &q) {//Initialize AQ.front = Q.rear = (queueptr)malloc(sizeof(Qnode)); -     if(!Q.front) - exit (OVERFLOW); theQ.front-Next =NULL; -     returnOK; - } -  +Status EnQueue (Linkqueue &q,qelemtype &e) {//put element e in the queue -p = (queueptr)malloc(sizeof(Qnode)); +     if(!p) A exit (OVERFLOW); atP-Next =NULL; -P-data =e; -Q.rear-Next =p; -Q.rear =p; -     returnOK; - } in  -Status Dequeue (Linkqueue &q,qelemtype &e) {//Delete the head element and save the top element of the team in E to     if(Q.front = =q.rear) +         returnERROR; -p = Q.frontNext; theE = Pdata; *Q.front-next = P-Next; $     if(Q.rear = =p)Panax NotoginsengQ.rear =Q.front; -      Free(p); the     returnOK; +}

2. Circular queue

1 #defineMaxqsize 1002 3typedefstruct{4Qelemtype *Base;5     intFront;6     intRear;7 }sqqueue;8 9Status Initqueue (Sqqueue &Q) {TenQ.Base= (Qelemtype *)malloc(maxqsize*sizeof(Qelemtype)); One     if(! Q.Base) A exit (OVERFLOW); -Q.front = Q.rear =0; -     returnOK; the } -  -Status EnQueue (Sqqueue &q,qelemtype &e) { -     if((q.rear+1)%maxqsize = = Q.front)//queue is full +         returnERROR; -Q.Base[Q.rear] =e; +Q.rear = (q.rear+1)%maxqsize; A     returnOK; at } -  -Status Dequeue (Sqqueue &q,qelemtype &e) { -     if(Q.front = =q.rear) -         returnERROR; -E = Q.Base[Q.front]; inQ.front = (q.front+1)%maxqsize; -     returnOK; to}

Queue and Loop queue

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.