#include<bits/stdc++.h> #define OK 1 #define ERROR 0 using namespace std;typedef int Status; typedef int ElemType;typedef struct QNode {ElemType data;struct QNode *next; }*Node;typedef struct {Node front;Node rear;int len; }LinkQueue; ///初始化 Status Init(LinkQueue &Q) {Node p;p=(Node)malloc(sizeof(QNode));if(p){Q.front=Q.rear=p;p->next=NULL;Q.len=0;return OK;}elsereturn ERROR; } ///判断队列是否为空 bool EmptyQueue(LinkQueue Q) {if(Q.front == Q.rear){return true;}else{return ERROR;} } ///入队 Status Push(LinkQueue &Q, ElemType e) {Node p;p=(Node)malloc(sizeof(QNode));if(!p)exit(1);p->data=e;p->next=NULL; ///注意此处,刚开始没有想到,只有 p->next = NULL 才确定p是尾部Q.rear->next=p;Q.rear=p;Q.len++;return OK; } ///出队 int Pop(LinkQueue &Q,ElemType &e) {if(Q.front == Q.rear){printf("链队列没有元素\n");return ERROR;}else{Node p;p=Q.front->next;e=p->data;Q.front->next=p->next;if(Q.rear == p)Q.rear=Q.front;free(p);Q.len--;return e;} } ///求队列长度 int QueueLength(LinkQueue Q) {return Q.len; } ///销毁队列 Status DestroyQueue(LinkQueue &Q) {while(Q.front){Q.rear=Q.front->next;free(Q.front);Q.front=Q.rear;}return OK; }///清空队列 Status ClearQueue(LinkQueue &Q) {DestroyQueue(Q);Init(Q);return OK; }/*另一种思路写法 Status ClearQueue(LinkQueue &Q) {Node p,q;p=Q.front->next;while(p){q=p;p=p->next;free(q);}Q.rear=Q.front;Q.len=0;return OK;}另一种思路写法*/Status Print(LinkQueue Q) {Node p;p=Q.front->next;while(p!=Q.rear){printf("%d--",p->data);p=p->next;}printf("%d\n",Q.rear->data);return OK; }int main() {int n;LinkQueue Q;Init(Q);printf("请输入入队元素(以0为结束标志):");while(~scanf("%d",&n)){if(n == 0)break;Push(Q,n);}if(EmptyQueue(Q))printf("YES,kong\n");elseprintf("NO kong\n");printf("队列的长度为:%d\n",QueueLength(Q));printf("遍历队首到队尾的元素:\n");Print(Q);printf("------------------------------\n");int e;printf("出队的队首元素为:%d\n",Pop(Q,e));printf("队列的长度为:%d\n",QueueLength(Q));printf("遍历队首到队尾的元素:\n");Print(Q);printf("------------------------------\n");printf("Clear queue...\n");ClearQueue(Q);if(EmptyQueue(Q))printf("YES,kong\n");elseprintf("NO kong\n");printf("------------------------------\n");return 0; } /* 1 2 3 4 5 0 */