1 //链式队列 2 #include<stdio.h> 3 #include<stdlib.h> 4 typedef int Status; 5 typedef struct node { 6 char a; 7 struct node* next; 8 }NODE; 9 typedef struct QueueLink { 10 NODE *front; 11 NODE *rear; 12 int count; 13 14 }QueueLink; 15 QueueLink *test_QueueLink; 16 void initQueueLink()//初始化链式队列 17 { 18 test_QueueLink = (QueueLink*)malloc(sizeof(QueueLink)); 19 //test_QueueLink->front = (NODE*)malloc(sizeof(NODE)); 20 //test_QueueLink->rear = (NODE*)malloc(sizeof(NODE)); 21 //test_QueueLink->front->next = NULL; 22 //test_QueueLink->rear->next = NULL; 23 test_QueueLink->front = NULL; 24 test_QueueLink->rear = NULL; 25 test_QueueLink->count = 0; 26 } 27 Status EnQueueLink(char p)//链式队列入列 28 { 29 NODE* temp = (NODE*)malloc(sizeof(NODE));//给入队的节点分配内存 30 if (temp == NULL) 31 { 32 perror("分配内存失败:"); 33 return 0; 34 } 35 if (test_QueueLink->front == NULL) //如果是空栈 36 { 37 temp->next = NULL; 38 temp->a = p; 39 test_QueueLink->rear = temp; //建立连接 40 test_QueueLink->front = temp; 41 test_QueueLink->count++; 42 return 1; 43 } 44 temp->next = NULL; 45 temp->a = p; 46 test_QueueLink->rear->next = temp;//移动尾指针指向的地址的下一个地址为temp 47 test_QueueLink->rear = temp; //移动尾指针指向下一个地址 48 test_QueueLink->count++; 49 return 1; 50 } 51 Status DeQueueLink() //链式队列出列 52 { 53 char c; 54 NODE* temp; 55 if (test_QueueLink->front->next == NULL)//如果说是最后一个数 56 { 57 temp = test_QueueLink->front; 58 c = temp->a; 59 free(temp); 60 temp = NULL; 61 printf("%c已出队列", c); 62 test_QueueLink->front = NULL; 63 test_QueueLink->rear = NULL;//删除当前节点并把头指针和尾指针指向NULL 64 test_QueueLink->count--; 65 return 1; 66 } 67 if (test_QueueLink->rear == NULL)//如果队列的头和尾都是指向NULL 68 { 69 printf("链式队列已空\n"); 70 return 0; 71 } 72 c = test_QueueLink->front->next->a;//读取链式队列的头部的内容 73 temp = test_QueueLink->front->next; 74 test_QueueLink->front->next = test_QueueLink->front->next->next;//移动链式队列的头部 75 printf("%c已出队列", c); 76 free(temp); 77 temp = NULL; //释放移动前的链式队列的头部 78 test_QueueLink->count--;//减少链式队列的总数 79 } 80 int main() 81 { 82 initQueueLink(); 83 EnQueueLink('a'); 84 EnQueueLink('b'); 85 EnQueueLink('c'); 86 printf("栈的大小为%d\n", test_QueueLink->count); 87 DeQueueLink(); 88 DeQueueLink(); 89 DeQueueLink(); 90 printf("栈的大小为%d\n", test_QueueLink->count); 91 return 0; 92 }
浙公网安备 33010602011771号