链式队列的初始化、销毁、入队、出队操作,测试用例为:将0~19入队,并打印输出结果
typedef int QElemType;
typedef struct QNode
{
QElemType data;
struct QNode *next;
}QNode, *QueuePtr;
typedef struct
{
QueuePtr front;
QueuePtr rear;
}LinkQueue;
/* 构造一个空的队列Q */
bool InitQueue(LinkQueue &Q)
{
Q.front = Q.rear = (QueuePtr)malloc(sizeof(QNode));
if (!Q.front)
{
printf("链队列创建失败!\n");
exit(1);
}
Q.front->next = NULL;
return TRUE;
}
/* 销毁队列 */
bool Destroy(LinkQueue &Q)
{
while (Q.front)
{
Q.rear = Q.front->next;
free(Q.front);
Q.front = Q.rear;
}
return TRUE;
}
/* 插入元素 */
bool EnQueue(LinkQueue &Q, QElemType e)
{
QNode *p = (QueuePtr)malloc(sizeof(QNode));
if (!p) exit(1);
p->data = e;
Q.rear->next = p;
p->next = NULL;
Q.rear = p;
return TRUE;
}
/* 删除元素 */
bool DeQueue(LinkQueue &Q, QElemType &e)
{
if (Q.front == Q.rear) return FALSE;
QNode *p;
p = Q.front->next;
e = p->data;
Q.front->next = p->next;
if (Q.rear == p) Q.rear = Q.front;
free(p);
return TRUE;
}
int main()
{
LinkQueue Q;
InitQueue(Q);
printf("输入的链队列!\n");
for (int i=0; i<20; ++i)
{
EnQueue(Q, i);
printf(" %d ",i);
}
printf("\n输出链队列元素!\n");
QElemType temp;
for (int i=0; i<20; ++i)
{
DeQueue(Q, temp);
printf(" %d ", temp);
}
printf("\n");
Destroy(Q);
system("pause");
return 0;
}