您的位置:首页 > 其它

循环队列一种实现

2017-09-22 19:18 295 查看
Queue实现方式有两种:数组和链表,本文属于数组实现,为了防止队列出现“明明还有存储空间,但是却提示队列已满”的情况,故使用循环队列

#include <stdio.h>
#include <stdlib.h>

#define MAX_SIZE 5
typedef struct Qnode {
int size;
int front;
int rear;
char data[MAX_SIZE];
}Squeue,*Squeueptr;

void init_squeue(Squeueptr *sq)
{
*sq = malloc(sizeof(Squeue));
if(*sq == NULL)
printf("Error: alloc memory failed!!\n");
else {
(*sq)->front = 0;
(*sq)->rear = 0;
(*sq)->size = 0;
(*sq)->data[0] = '\0';
}
}

int ensqueue(Squeueptr sq, char e)
{
if(sq == NULL) {
printf("Error:this squeue don't exsit!!\n");
return -1;
}

if(sq->front == (sq->rear + 1)%MAX_SIZE) {
printf("Error:this squeue already full!!\n");
return -1;
}
sq->data[sq->rear] = e;
sq->rear++;
if(sq->rear == MAX_SIZE)
sq->rear = 0;
sq->data[sq->rear] = '\0';
return 0;
}

int desqueue(Squeueptr sq, char *e)
{
if(sq == NULL) {
printf("Error:this squeue don't exsit!!\n");
return -1;
}

if(sq->front == sq->rear) {
printf("Error:this squeue already empty!!\n");
return -1;
}

*e = sq->data[sq->front];
sq->data[sq->front] = '\0';
sq->front++;
if(sq->front == MAX_SIZE)
sq->front = 0;
return 0;
}

void print_squeue(Squeueptr sq)
{
int i;

if(sq == NULL) {
printf("Error:this squeue don't exsit!!\n");
return;
}

for(i=0;i<MAX_SIZE;i++)
printf("yxw test0911: data[%d] = %c\n",i,sq->data[i]);

printf("yxw test0911: front = %d\n",sq->front);
printf("yxw test0911: rear = %d\n",sq->rear);
}

int main(void)
{
Squeueptr sq;
char c;
int n;

init_squeue(&sq);

while(1) {

printf("---------menu display-----------------\n");
printf("---------0: enqueue a data-----------------\n");
printf("---------1: dequeue a data-----------------\n");
printf("---------3: display a queue-----------------\n");

scanf("%d",&n);
getchar();
switch(n){
case 0:
printf("please input a data to add: ");
scanf("%c",&c);
ensqueue(sq,c);
break;
case 1:
if(!desqueue(sq,&c))
printf("this is c = %c\n",c);
break;
case 2:
print_squeue(sq);
break;

default:
print_squeue(sq);
break;
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: