#include "stdio.h" #include "stdlib.h" #include "io.h" #include "math.h" #include "time.h"#define OK 1 #define ERROR 0 #define TRUE 1 #define FALSE 0 #define MAXSIZE 20 /* 存儲空間初始分配量 */typedef int Status; typedef int QElemType; /* QElemType類型根據實際情況而定,這里假設為int */typedef struct QNode /* 結點結構 */ {QElemType data;struct QNode *next; }QNode,*QueuePtr;typedef struct /* 隊列的鏈表結構 */ {QueuePtr front,rear; /* 隊頭、隊尾指針 */ }LinkQueue;Status visit(QElemType c) {printf("%d ",c);return OK; }/* 構造一個空隊列Q */ Status InitQueue(LinkQueue *Q) { Q->front=Q->rear=(QueuePtr)malloc(sizeof(QNode));if(!Q->front)exit(OVERFLOW);Q->front->next=NULL;return OK; }/* 銷毀隊列Q */ Status DestroyQueue(LinkQueue *Q) {while(Q->front){Q->rear=Q->front->next;free(Q->front);Q->front=Q->rear;}return OK; }/* 將Q清為空隊列 */ Status ClearQueue(LinkQueue *Q) {QueuePtr p,q;Q->rear=Q->front;p=Q->front->next;Q->front->next=NULL;while(p){q=p;p=p->next;free(q);}return OK; }/* 若Q為空隊列,則返回TRUE,否則返回FALSE */ Status QueueEmpty(LinkQueue Q) { if(Q.front==Q.rear)return TRUE;elsereturn FALSE; }/* 求隊列的長度 */ int QueueLength(LinkQueue Q) { int i=0;QueuePtr p;p=Q.front;while(Q.rear!=p){i++;p=p->next;}return i; }/* 若隊列不空,則用e返回Q的隊頭元素,并返回OK,否則返回ERROR */ Status GetHead(LinkQueue Q,QElemType *e) { QueuePtr p;if(Q.front==Q.rear)return ERROR;p=Q.front->next;*e=p->data;return OK; }/* 插入元素e為Q的新的隊尾元素 */ Status EnQueue(LinkQueue *Q,QElemType e) { QueuePtr s=(QueuePtr)malloc(sizeof(QNode));if(!s) /* 存儲分配失敗 */exit(OVERFLOW);s->data=e;s->next=NULL;Q->rear->next=s; /* 把擁有元素e的新結點s賦值給原隊尾結點的后繼,見圖中① */Q->rear=s; /* 把當前的s設置為隊尾結點,rear指向s,見圖中② */return OK; }/* 若隊列不空,刪除Q的隊頭元素,用e返回其值,并返回OK,否則返回ERROR */ Status DeQueue(LinkQueue *Q,QElemType *e) {QueuePtr p;if(Q->front==Q->rear)return ERROR;p=Q->front->next; /* 將欲刪除的隊頭結點暫存給p,見圖中① */*e=p->data; /* 將欲刪除的隊頭結點的值賦值給e */Q->front->next=p->next;/* 將原隊頭結點的后繼p->next賦值給頭結點后繼,見圖中② */if(Q->rear==p) /* 若隊頭就是隊尾,則刪除后將rear指向頭結點,見圖中③ */Q->rear=Q->front;free(p);return OK; }/* 從隊頭到隊尾依次對隊列Q中每個元素輸出 */ Status QueueTraverse(LinkQueue Q) {QueuePtr p;p=Q.front->next;while(p){visit(p->data);p=p->next;}printf("\n");return OK; }int main() {int i;QElemType d;LinkQueue q;i=InitQueue(&q);if(i)printf("成功地構造了一個空隊列!\n");printf("是否空隊列?%d(1:空 0:否) ",QueueEmpty(q));printf("隊列的長度為%d\n",QueueLength(q));EnQueue(&q,-5);EnQueue(&q,5);EnQueue(&q,10);printf("插入3個元素(-5,5,10)后,隊列的長度為%d\n",QueueLength(q));printf("是否空隊列?%d(1:空 0:否) ",QueueEmpty(q));printf("隊列的元素依次為:");QueueTraverse(q);i=GetHead(q,&d);if(i==OK)printf("隊頭元素是:%d\n",d);DeQueue(&q,&d);printf("刪除了隊頭元素%d\n",d);i=GetHead(q,&d);if(i==OK)printf("新的隊頭元素是:%d\n",d);ClearQueue(&q);printf("清空隊列后,q.front=%u q.rear=%u q.front->next=%u\n",q.front,q.rear,q.front->next);DestroyQueue(&q);printf("銷毀隊列后,q.front=%u q.rear=%u\n",q.front, q.rear);return 0; }
?