1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97
| #include <stdio.h> #include <stdlib.h>
typedef struct Queue{ int len; int front; int rear; int * pBase; }Queue;
void init(Queue *); void en_queue(Queue *,int); void traverse_queue(Queue *); void out_queue(Queue *); void destroy(Queue *); void clear(Queue *);
int main(){ Queue Q; printf("请输入您需要的循环队列的长度:\n"); scanf("%d",&(Q.len)); init(&Q); en_queue(&Q, 1); en_queue(&Q, 2); en_queue(&Q, 3); en_queue(&Q, 4); en_queue(&Q, 5); en_queue(&Q, 6); en_queue(&Q, 7); en_queue(&Q, 8); traverse_queue(&Q); out_queue(&Q); traverse_queue(&Q); out_queue(&Q); traverse_queue(&Q); out_queue(&Q); traverse_queue(&Q); out_queue(&Q); traverse_queue(&Q); destroy(&Q); printf("%p",Q.pBase); return 0; }
void init(Queue* pQ){ pQ->pBase = (int*)malloc(sizeof(int)*(pQ->len)); pQ->front = 0; pQ->rear = 0; }
void en_queue(Queue* pQ,int val){ if ((pQ->rear+1)%pQ->len == pQ->front){ printf("队列已满!%d入队失败\n",val); }else{ pQ->pBase[pQ->rear] = val; pQ->rear = (pQ->rear+1) % pQ->len; } return; }
void traverse_queue(Queue* pQ){ if (pQ->rear == pQ->front){ printf("队列为空!\n"); }else{ int i = pQ->front; while (i != pQ->rear) { printf("%d ",pQ->pBase[i]); i = (i+1) % pQ->len; } } printf("\n"); return; }
void out_queue(Queue *pQ){ if (pQ->rear == pQ->front){ printf("队列为空!\n"); }else{ int val = pQ->pBase[pQ->front]; pQ->front = (pQ->front+1) % pQ->len; printf("出队的元素值为:%d\n",val); } return; }
void destroy(Queue *pQ){ pQ->len=-1; free(pQ->pBase); return; }
void clear(Queue *pQ){ pQ->len = 0; pQ->front = 0; pQ->rear = 0; return; }
|