循环队列及C语言实现一
循環(huán)隊(duì)列是為了充分利用內(nèi)存,進(jìn)行數(shù)據(jù)操作的一種基本算法。具體實(shí)現(xiàn)方式可劃分為:鏈?zhǔn)疥?duì)列和靜態(tài)隊(duì)列,這里所謂的靜態(tài)是指在一片連續(xù)的內(nèi)存區(qū)域進(jìn)行數(shù)據(jù)操作。本文只講述靜態(tài)隊(duì)列,也是最簡(jiǎn)單的實(shí)現(xiàn)方式,鏈?zhǔn)疥?duì)列以及鏈表的實(shí)現(xiàn)內(nèi)容請(qǐng)參見(jiàn)我的其它博文。以下靜態(tài)循環(huán)隊(duì)列簡(jiǎn)稱(chēng)為循環(huán)隊(duì)列。
一、循環(huán)隊(duì)列的特點(diǎn)及要素
<1> 先進(jìn)先出(FIFO);
<2> 首尾元素 front 和 rear 的數(shù)值;
<3> 隊(duì)列操作: 隊(duì)列初始化、銷(xiāo)毀隊(duì)列、遍歷隊(duì)列、隊(duì)列滿、隊(duì)列空、入隊(duì)列,出隊(duì)列。
<4> 隊(duì)列滿判斷的兩種方式:因?yàn)樾枰獏^(qū)分與隊(duì)列空時(shí) front 與 rear 的位置關(guān)系。
方式一:front == rear 并且 flag_full = true;
方式二:front= (rear + 1) % size;
二、具體實(shí)現(xiàn)及輸出結(jié)果見(jiàn)下面程序,因?yàn)檩^為簡(jiǎn)單,不作注解了。有疑問(wèn)可以 send comments to me。
#include <stdio.h> #include <stdlib.h>typedef struct queue{char *buf;int front;int rear;int size; } Queue, *pQueue;void Init_Queue(Queue *q, int maxsize) {q->buf = (char *)malloc(sizeof(char) * maxsize);if (q->buf == NULL) {perror("malloc error: ");exit(1);}q->front = 0;q->rear = 0;q->size = maxsize; }void Destroy_Queue(Queue *q) {free(q->buf); }void Traverse_Queue(Queue *q) {int i = q->front;while (i % q->size != q->rear) {printf("buf[%d]: %d\n", i, q->buf[i]);i++;} }bool Queue_Empty(Queue *q) {return (q->front == q->rear); }bool Queue_Full(Queue *q) {return (q->front == ((q->rear + 1) % q->size)); }bool EnQueue(Queue *q, char val) {if (!Queue_Full(q)) {*(q->buf + q->rear) = val;q->rear = (q->rear + 1) % q->size;return true;}printf("Queue Full!\n");return false; }bool DeQueue(Queue *q, char *val) {if(!Queue_Empty(q)) {*val = *(q->buf + q->front);q->front = (q->front + 1) % q->size;return true;} printf("Queue Empty!\n");return false; }void main() {Queue q;char a;Init_Queue(&q, 6);printf("Input queue elements: \n");while(!Queue_Full(&q)) {scanf("%d", &a);EnQueue(&q, a);}printf("Traverse queue elements: \n");Traverse_Queue(&q);printf("Delete queue elements: \n");while(!Queue_Empty(&q)) {DeQueue(&q, &a);printf("%d\n", a);}Destroy_Queue(&q); }程序運(yùn)行結(jié)果:
關(guān)于循環(huán)隊(duì)列主題的系列文章,可移步至以下鏈接:
1. 《循環(huán)隊(duì)列及C語(yǔ)言實(shí)現(xiàn)<一>》
2. 《循環(huán)隊(duì)列及C語(yǔ)言實(shí)現(xiàn)<二>》
3. 《循環(huán)隊(duì)列及C語(yǔ)言實(shí)現(xiàn)<三>》
總結(jié)
以上是生活随笔為你收集整理的循环队列及C语言实现一的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。