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
| #include <stdio.h> #include <stdlib.h>
#define MaxSize 5 typedef int ElemType; typedef struct { ElemType data[MaxSize]; int front, rear; } SqQueue;
void initQueue(SqQueue &Q) { Q.front = Q.rear = 0; }
bool isEmpty(SqQueue Q) {
return Q.front == Q.rear; }
bool enQueue(SqQueue &Q, ElemType e) { if ((Q.rear + 1) % MaxSize == Q.front) { return false; } Q.data[Q.rear] = e; Q.rear = (Q.rear + 1) % MaxSize; return true; }
bool deQueue(SqQueue &Q, ElemType &e) { if (Q.front == Q.rear) { return false; } e = Q.data[Q.front]; Q.front = (Q.front + 1) % MaxSize; return true; }
int main() { SqQueue Q; initQueue(Q); bool ret; ret = isEmpty(Q); if (ret) { printf("队列为空"); } else { printf("队列不为空"); } enQueue(Q, 3); enQueue(Q, 4); enQueue(Q, 5); ret = enQueue(Q, 6); ret = enQueue(Q, 7); if (ret) { printf("入队成功\n"); } else { printf("入队失败\n"); } ElemType elem; ret = deQueue(Q, elem); if (ret) { printf("出队成功,出队元素:%d\n", elem); } else { printf("出队失败\n", elem); } ret = enQueue(Q, 7); if (ret) { printf("入队成功\n"); } else { printf("入队失败\n"); } return 0; }
|