# include <stdio.h> # include <malloc.h> # include <stdbool.h> typedef struct Queue{ int * pBase; int len; int front; int rear; } QUEUE, * pQUEUE; void init_queue(pQUEUE); bool bool_en_queue(pQUEUE, int); bool bool_de_queue(pQUEUE); bool bool_full_queue(pQUEUE); bool bool_empty_queue(pQUEUE); void traverse_queue(pQUEUE); int main (void){ QUEUE queue; init_queue(&queue); bool_empty_queue(&queue); bool_en_queue(&queue, 1); bool_en_queue(&queue, 2); bool_en_queue(&queue, 3); bool_en_queue(&queue, 4); bool_en_queue(&queue, 5); bool_de_queue(&queue); traverse_queue(&queue); return 0; } void init_queue(pQUEUE pQueue){ printf("请输入队列长度:"); scanf("%d", &(pQueue->len)); pQueue->pBase = (int *) malloc(sizeof(int) * pQueue->len); pQueue->front = 0; pQueue->rear = 0; } bool bool_en_queue(pQUEUE pQueue, int val){ if(bool_full_queue(pQueue)){ printf("队列满,无法添加元素:%d\n", val); return false; } pQueue->pBase[pQueue->rear] = val; pQueue->rear = (pQueue->rear + 1) % (pQueue->len); return true; } bool bool_de_queue(pQUEUE pQueue){ if(bool_empty_queue(pQueue)){ printf("队列空,无法删除!"); return false; } else{ printf("删除的元素:%d\n", pQueue->pBase[pQueue->front]); pQueue->front = (pQueue->front + 1) % pQueue->len; return true; } } bool bool_full_queue(pQUEUE pQueue){ int dot = (pQueue->rear + 1) % (pQueue->len); if(dot == pQueue->front){ return true; } else{ return false; } } bool bool_empty_queue(pQUEUE pQueue){ if(pQueue->rear == pQueue->front){ printf("队列空!\n"); return true; } else{ return false; } } void traverse_queue(pQUEUE pQueue){ if(bool_empty_queue(pQueue)){ printf("队列空,无法遍历!\n"); } else{ printf("队列中元素:\n"); } while (pQueue->front != pQueue->rear){ printf("%d ", pQueue->pBase[pQueue->front]); pQueue->front = (pQueue->front + 1) % pQueue->len; } printf("\n"); }
数据结构//C——静态队列(数组)
于 2022-01-26 11:24:52 首次发布