迴圈隊列的實現

來源:互聯網
上載者:User

同樣老師不讓直接用queue這個容器,所以自己實現咯。
迴圈隊列很厲害呢。。

#include<cstdio>#include<cstdlib>using namespace std;const int MAXSIZE = 100;typedef struct{    int *base;    int front;    int rear; }SqQueue;/*初始化隊列*/bool Init(SqQueue &q){    q.base = (int *)malloc(MAXSIZE*sizeof(int));    if(!q.base) return 0;    q.front = q.rear = 0;    return 1;}/*求隊列長度*/int QueueLength(SqQueue &q){    return (q.rear - q.front + MAXSIZE) % MAXSIZE;}/*判斷隊列是否為空白*/bool IsEmpty(SqQueue q){    return q.front == q.rear;} /*取隊頭元素*/bool GetFront(SqQueue &q, int &e){    if(IsEmpty(q)) return 0;    e = q.base[q.front];    return 1;}/*入隊*/bool EnQueue(SqQueue &q, int e){    if((q.rear+1)%MAXSIZE == q.front) return 0;//隊滿    q.base[q.rear] = e;    q.rear = (q.rear+1) % MAXSIZE;    return 1; }/*出隊*/bool DeQueue(SqQueue &q){    if(q.front == q.rear) return 0;//隊空    q.front = (q.front+1) % MAXSIZE;     return 1;} /*列印佇列,並清空隊列*/void PrintQueue(SqQueue &q){    printf("此時隊列為:");     while(!IsEmpty(q))    {        int e;        GetFront(q, e);        printf("%d ",e);        DeQueue(q);    }}int main(){    SqQueue q;    Init(q);    while(1)    {        printf("\n");        printf("1.入隊  2.出隊  3.輸出隊首元素  4.查詢隊列長度  5.退出 :");        int choose;        scanf("%d",&choose);        if(choose == 5) break;        int e;        switch(choose)        {            case 1:                printf("輸入要入隊的元素:");                scanf("%d",&e);                if(!EnQueue(q, e)) printf("隊已滿\n");                break;            case 2:                if(!DeQueue(q))                printf("隊已空\n");                break;                      case 3:                if(GetFront(q, e)) printf("隊首元素為 %d\n",e);                else printf("隊已空\n");                break;              case 4:                printf("隊列長度為 %d\n",QueueLength(q));                break;          }    }    PrintQueue(q);    return 0;}

運行圖:

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.