隊列(轉載)

來源:互聯網
上載者:User

標籤:

隊列特性:先進先出(FIFO)——先進隊列的元素先出隊列。來源於我們生活中的隊列(先排隊的先辦完事)。

隊列有下面幾個操作:

  • InitQueue()   ——初始化隊列
  • EnQueue()        ——進隊列
  • DeQueue()        ——出隊列
  • IsQueueEmpty()——判斷隊列是否為空白
  • IsQueueFull()    ——判斷隊列是否已滿

隊列可以由數組和鏈表兩種形式實現隊列操作(c語言),下面僅以數組為例:

數組實現:

隊列資料結構

typedef struct queue{        int queuesize;   //數組的大小        int head, tail;  //隊列的頭和尾下標        int *q;          //數組頭指標}Queue;

InitQueue()   ——初始化隊列

void InitQueue(Queue *q){        q->queuesize = 8;        q->q = (int *)malloc(sizeof(int) * q->queuesize); //分配記憶體        q->tail    = 0;        q->head = 0;}

這樣有個缺陷,空間利用率不高。採用迴圈隊列:

 

EnQueue()        ——進隊列

void EnQueue(Queue *q, int key){        int tail = (q->tail+1) % q->queuesize; //取餘保證,當quil=queuesize-1時,再轉回0        if (tail == q->head)                   //此時隊列沒有空間        {            printf("the queue has been filled full!");        }        else        {            q->q[q->tail] = key;            q->tail = tail;        }}

DeQueue()        ——出隊列

int DeQueue(Queue *q){        int tmp;        if(q->tail == q->head)     //判斷隊列不為空白        {            printf("the queue is NULL\n");        }        else        {            tmp = q->q[q->head];            q->head = (q->head+1) % q->queuesize;        }        return tmp;}

IsQueueEmpty()——判斷隊列是否為空白

int IsQueueEmpty(Queue *q){        if(q->head == q->tail)        {            return 1;        }        else        {            return 0;        }}

IsQueueFull()——判斷隊列是否已滿

int IsQueueFull(Queue *q){    if((q->tail+1)% q->queuesize == q->head)    {        return 1;    }    else    {        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.