程序在vc2005上编译通过,实现了数据插入和删除的操作,插入是在队列头插入数据,删除是在队列尾删除数据。
程序源码
#include<stdio.h>
#define MAX_ELEM_LEN 10
typedef struct
{
int data;
}Element;
typedef struct Queue
{
Element elem_array[MAX_ELEM_LEN];
int head;
int tail;
}CircularQueue;
CircularQueue cq;
Element cqarray[10];
Element val;
int i;
bool QueueIsEmpty(CircularQueue *q)
{
if(q->head == q->tail)
{
return true;
}
else
{
return false;
}
}
bool QueueIsFull(CircularQueue *q)
{
if((q->tail + 1)%MAX_ELEM_LEN == q->head)
{
return true;
}
else
{
return false;
}
}
void InitQueue(CircularQueue *q)
{
q->head = 0;
q->tail = 0;
}
void InsertQueue(CircularQueue *q, Element e)
{
if(QueueIsFull(q))
{
printf("The queue is Full.\n");
}
else
{
q->elem_array[q->tail] = e;
q->tail = (q->tail + 1)% MAX_ELEM_LEN;
}
}
void DeleteQueue(CircularQueue *q,Element *e)
{
if(QueueIsEmpty(q))
{
printf("Queue is Empty.\n");
}
else
{
*e = q->elem_array[q->head];
q->head = (q->head + 1) % MAX_ELEM_LEN;
}
}
void TraverseQueue(CircularQueue *q)
{
int val = q->head;
while(val != q->tail)
{
printf("%d ",q->elem_array[val].data);
val = (val + 1) % MAX_ELEM_LEN;
}
}
int main(void)
{
printf("hello world!\n");
InitQueue(&cq);
printf("Input data %d:",sizeof(cqarray));
for(i=0;i<(sizeof(cqarray)/4);i++)
{
cqarray[i].data = i;
printf("%d,",cqarray[i].data);
}
printf("\n");
for(i=0;i<sizeof(cqarray)/4;i++)
{
InsertQueue(&cq,cqarray[i]);
printf("Insert queue Element:%d \n",cq.elem_array[i].data);
TraverseQueue(&cq);
printf("\n");
}
while(!QueueIsEmpty(&cq))
{
DeleteQueue(&cq,&val);
printf("DelteQueue Element is:%d\n",val);
TraverseQueue(&cq);
printf("\n");
}
}
执行程序后的结果:
hello world!
Input data 40:0,1,2,3,4,5,6,7,8,9,
Insert queue Element:0
0
Insert queue Element:1
0 1
Insert queue Element:2
0 1 2
Insert queue Element:3
0 1 2 3
Insert queue Element:4
0 1 2 3 4
Insert queue Element:5
0 1 2 3 4 5
Insert queue Element:6
0 1 2 3 4 5 6
Insert queue Element:7
0 1 2 3 4 5 6 7
Insert queue Element:8
0 1 2 3 4 5 6 7 8
The queue is Full.
Insert queue Element:0
0 1 2 3 4 5 6 7 8
DelteQueue Element is:0
1 2 3 4 5 6 7 8
DelteQueue Element is:1
2 3 4 5 6 7 8
DelteQueue Element is:2
3 4 5 6 7 8
DelteQueue Element is:3
4 5 6 7 8
DelteQueue Element is:4
5 6 7 8
DelteQueue Element is:5
6 7 8
DelteQueue Element is:6
7 8
DelteQueue Element is:7
8
DelteQueue Element is:8
请按任意键继续. . .