20.链式队列
运行截图:
完整代码:
1 #include <stdio.h> 2 #include <stdlib.h> 3 4 #define datatype int 5 6 typedef struct queue 7 { 8 datatype data; 9 struct queue *pNext; 10 }Queue,*PQueue; 11 12 //入队 从尾部入,从头部出 13 PQueue enq(PQueue phead, datatype data) 14 { 15 PQueue pnew = (PQueue)malloc(sizeof(Queue)); 16 pnew->data = data; 17 pnew->pNext = NULL; 18 if (phead == NULL) 19 { 20 phead = pnew;//直接插入 21 } 22 else 23 { 24 PQueue ptemp = phead; 25 //循环到尾部 26 while (ptemp->pNext != NULL) 27 { 28 ptemp = ptemp->pNext; 29 } 30 ptemp->pNext = pnew;//尾部插入 31 } 32 return phead; 33 } 34 35 //出队 36 PQueue deq(PQueue phead, datatype *pdata) 37 { 38 if (phead == NULL) 39 { 40 return NULL; 41 } 42 else 43 { 44 *pdata = phead->data;//获取弹出的数据 45 PQueue ptemp = phead->pNext; 46 free(phead); 47 phead = ptemp; 48 } 49 } 50 51 //显示 52 void show(PQueue phead) 53 { 54 if (phead == NULL) 55 { 56 return; 57 } 58 else 59 { 60 printf("%5d", phead->data); 61 show(phead->pNext);//递归调用 62 } 63 } 64 65 void main() 66 { 67 Queue *phead = NULL; 68 for (int i = 0; i < 10; i++) 69 { 70 phead = enq(phead, i); 71 printf("\nqueue"); 72 show(phead); 73 } 74 75 while (phead != NULL) 76 { 77 datatype data; 78 phead = deq(phead, &data); 79 printf("\ndequeue%d", data); 80 printf("\nqueue"); 81 show(phead); 82 } 83 84 system("pause"); 85 }