您的位置:首页 > 编程语言 > C语言/C++

c语言实现循环队列

2015-04-16 00:04 295 查看
#include<stdbool.h>
#include<stdio.h>
#include<malloc.h>
typedef int Item;
#define MAXQUEUE 10
typedef struct queue{
int front;
int rear;
int data[MAXQUEUE];
}Queue;
void InitQueue(Queue *pq)
{
pq->front = pq->rear = 0;
}
bool QueueIsFull(const Queue *pq)
{
return ((pq->rear+1)%MAXQUEUE == pq->front)?1:0;
}
bool QueueIsEmpty(const Queue *pq)
{
return (pq->rear == pq->front)?1:0;
}
int QueueItemCount(const Queue *pq)
{
return (pq->rear - pq->front + MAXQUEUE)%MAXQUEUE;
}
bool EnQueue(Item item,Queue *pq)
{
if(QueueIsFull(pq))
return 0;
pq->data[pq->rear] = item;
pq->rear = (pq->rear + 1)%MAXQUEUE;
return 1;
}
bool DeQueue(Queue *pq,Item *data)
{
if(QueueIsEmpty(pq))
return 0;
*data = pq->data[pq->front];
pq->front = (pq->front + 1)%MAXQUEUE;
return 1;
}
int main(void)
{
Queue line;
Item temp;
char ch;
InitQueue(&line);
while((ch = getchar()) != 'q')
{
if((ch != 'a')&&(ch != 'd'))
continue;
if(ch == 'a'){
printf("scanf temp\n");
scanf("%d",&temp);
if(!QueueIsFull(&line)){
printf("will enter %d temp into line.\n",temp);
EnQueue(temp,&line);
}else{
printf("the queue is full.\n");
}
}else if(ch == 'd'){
if(!QueueIsEmpty(&line)){
DeQueue(&line,&temp);
printf("out queue data=%d\n",temp);
}else{
printf("the queue is empty.\n");
}
}
}
}
以上代码通过测试可以正常运行的,详细与前一篇的单向队列差不多,大家可以参考代码理解下
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: