采用循环顺序方式存储队列,测试用例为:将0~9入队,然后打印输出,代码如下:
#define MAXQSIZE 100
typedef struct
{
QElemType data[MAXQSIZE];
int front,rear;
}SqQueue;
/* 初始化队列 */
void InitiQueue(SqQueue &Q)
{
Q.front = Q.rear = 0;
}
/* 判队列是否为空 */
bool isEmpty(SqQueue &Q)
{
if (Q.rear == Q.front) return TRUE;
return FALSE;
}
/* 入队 */
bool EnQueue(SqQueue &Q, QElemType &e)
{
if ((Q.rear+1)%MAXQSIZE == Q.front)
{
printf("队列已满,不能加入新元素!\n");
return FALSE;
}
Q.data[Q.rear] = e;
Q.rear = (Q.rear+1)%MAXQSIZE;
return TRUE;
}
/* 出队 */
bool DeQueue(SqQueue &Q, QElemType &e)
{
if (isEmpty(Q))
{
printf("队列为空,,没有元素!\n");
return FALSE;
}
e = Q.data[Q.front];
Q.front = (Q.front+1)%MAXQSIZE;
return TRUE;
}
int main()
{
SqQueue SQ;
InitiQueue(SQ);
printf("输入的队列元素值为:\n");
for (int i=0; i<10; ++i) {
EnQueue(SQ, i);
printf(" %d ", i);
}
printf("\n打印队列元素值!\n");
QElemType temp[10];
for (int i=0; i<10; ++i) {
DeQueue(SQ, temp[i]);
printf(" %d ", temp[i]);
}
printf("\n");
system("pause");
return 0;
}