#include <stdio.h>
#include <stdlib.h>
#define ElemType int
#define Status int
#define OK 1
#define ERROR 0
typedef struct QNode{
ElemType data;
struct QNode *next;
}QNode;
typedef struct LinkQueue{
QNode *front;
QNode *rear;
}LinkQueue;
Status InitQueue(LinkQueue *q) { //建立队列
q->front=q->rear=(QNode *)malloc(sizeof(QNode));
if(!q->front)
return ERROR;
q->front->next=NULL;
return OK;
}
Status EnQueue(LinkQueue *q,ElemType e) { //入队
QNode *p=(QNode *)malloc(sizeof(QNode));
if(!p)
return ERROR;
p->data=e;
p->next=NULL;
q->rear->next=p; //入队操作,从队尾(rear)进入
q->rear=p;
return OK;
}
Status DeQueue(LinkQueue *q,ElemType *e) { //出队
QNode *p=(QNode *)malloc(sizeof(QNode));
if(!p)
return ERROR;
p=q->front->next; //q指向的是front指针的下一个位置,亦即队首元素
*e=p->data;
q->front->next=p->next; //出队操作后,front++
if(q->rear==p) //判断是否全部出队
q->rear=q->front; //如果全部出队,则将队列置为空
return OK;
}
Status PrintfQueue(LinkQueue *Q) {
QNode *p;
for(p=Q->front->next;p!=NULL;p=p->next)
printf("%d\t",p->data);
}
int main(void)
{
int i,n;
ElemType e,de;
LinkQueue *q=(LinkQueue *)malloc(sizeof(QNode));
if(!q)
return ERROR;
InitQueue(q);
printf("以下开始构造初始队列:\n\n");
printf("请输入元素个数:");
scanf("%d",&n);
printf("\n");
for(i=0;i<n;++i) {
printf("请输入第%d个元素:",i+1);
scanf("%d",&e);
EnQueue(q,e);
}
printf("\n");
printf ("初始队列构造完毕!\n\n");
printf ("初始队列:\n");
PrintfQueue(q);
printf("\n\n");
printf ("======================================================\n\n");
printf("以下开始执行入队操作:\n\n");
printf("请输入需入队的元素个数:");
scanf("%d",&n);
printf("\n");
for(i=0;i<n;++i) {
printf("请输入第%d个元素:",i+1);
scanf("%d",&e);
EnQueue(q,e);
}
printf("\n");
printf ("入队%d个元素操作完毕!\n\n",n);
printf("此时队列:\n");
PrintfQueue(q);
printf("\n\n");
printf ("======================================================\n\n");
printf("以下开始执行出队操作:\n\n");
printf("请输入需出队的元素个数:");
scanf("%d",&n);
printf("\n");
for(i=0;i<n;++i)
DeQueue(q,&de);
printf("\n");
printf ("出队%d个元素操作完毕!\n\n",n);
printf("此时队列:\n");
PrintfQueue(q);
printf("\n\n");
printf ("======================================================\n\n");
free(q);
return 0;
}
执行结果