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 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133
| #include <stdio.h> #include <stdlib.h> #include <stdbool.h>
#define MAXSIZE 10
typedef int ElemType;
typedef struct queue { ElemType * pBase; int front; int rear; } Queue, *pQueue;
void InitQueue(pQueue pQ); bool IsFull(pQueue pQ); bool EnQueue(pQueue pQ, ElemType e); bool IsEmpty(pQueue pQ); bool TraverQe(pQueue pQ); bool DeQueue(pQueue pQ, ElemType * pE);
int main(void) { Queue Q;
InitQueue(&Q);
printf("入队:"); EnQueue(&Q, 1); EnQueue(&Q, 2); EnQueue(&Q, 3); EnQueue(&Q, 4); EnQueue(&Q, 5); EnQueue(&Q, 6);
TraverQe(&Q);
ElemType e; DeQueue(&Q, &e); printf("出队:%d\n", e); DeQueue(&Q, &e); printf("出队:%d\n", e); DeQueue(&Q, &e); printf("出队:%d\n", e);
TraverQe(&Q);
return 0;
}
void InitQueue(pQueue pQ) { pQ->pBase = (ElemType*)malloc( MAXSIZE * sizeof(ElemType) ); pQ->front = 0; pQ->rear = 0; }
bool IsFull(pQueue pQ) { return ( (pQ->rear+1) % MAXSIZE == pQ->front ); }
bool EnQueue(pQueue pQ, ElemType e) { if ( IsFull(pQ) ) { printf("队列已满!无法入队!"); return false; }
pQ->pBase[pQ->rear] = e; pQ->rear = (pQ->rear + 1) % MAXSIZE;
return true; }
bool IsEmpty(pQueue pQ) { return ( pQ->front == pQ->rear ); }
bool TraverQe(pQueue pQ) { if ( IsEmpty(pQ) ) { printf("队列为空!"); return false; }
int i = pQ->front; while ( i != pQ->rear ) { printf("%d ", pQ->pBase[i]); i = (i + 1) % MAXSIZE; } printf("\n");
return true; }
bool DeQueue(pQueue pQ, ElemType * pE) { if ( IsEmpty(pQ) ) { printf("队列为空!"); return false; }
*pE = pQ->pBase[pQ->front]; pQ->front = (pQ->front + 1) % MAXSIZE;
return true; }
|