隊列-基本操作(C版)

來源:互聯網
上載者:User

隊列也是表,使用隊列時,插入在一端進行,而刪除在另一端進行。

常用的操作:

/**是否為空白隊列**/int isEmpty(Queue q)/**隊列是否已滿**/int isFull(Queue q)/**實現迴圈隊列,重設rear或者front**/int circularQ(int index,Queue q)/*入列*/void enQueue(Queue q,int item)/*出列*/int deQueue(Queue q)/**取隊列頭元素**/int front(Queue q)

Queue.c

#include <stdio.h>#include <stdlib.h>typedef struct QueueRec{int front;int rear;int size;//隊列元素個數int capacity;//隊列大小int *Array;} lqueue,*Queue;int isEmpty(Queue q){return q->size==0;}int isFull(Queue q){return q->size==q->capacity;}Queue createQueue(int capacity){Queue queue;queue = (Queue)malloc(sizeof(lqueue));if(queue==NULL){return NULL;}queue->Array = malloc(sizeof(int)*capacity);if(queue->Array == NULL ){return NULL;}queue->capacity = capacity;queue->size = 0;queue->front = 0;queue->rear = -1;return queue;}void makEmpty(Queue q){q->size = 0;q->rear = -1;q->front = 0;}void disPoseQueue(Queue q){if(q!=NULL){free(q);}}/**這個方法實現迴圈隊列,當rear到達尾端(入列),或者front到達尾端(出列),它又回到開頭**/int circularQ(int index,Queue q){if(++index > q->capacity){return 0;}return index;}/*入列*/void enQueue(Queue q,int item){if(isFull(q)){printf("Queue is Full\n");} else {q->size ++;q->rear = circularQ(q->rear,q);q->Array[q->rear] = item;}}/*出列*/int deQueue(Queue q){int temp;if(isEmpty(q)){printf("queue is Empty\n");} else {q->size --;temp = q->Array[q->front];q->front = circularQ(q->front,q);}return temp;}/**取隊列頭元素**/int front(Queue q){return q->Array[q->front];}int main(void){Queue q = createQueue(5);enQueue(q,1);enQueue(q,2);enQueue(q,3);enQueue(q,4);enQueue(q,5);enQueue(q,6);printf("%d\n",front(q));printf("%d\n",deQueue(q));printf("%d\n",deQueue(q));enQueue(q,7);printf("%d\n",front(q));disPoseQueue(q);return -1;}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.