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
| #include <stdio.h> #define MAX_SIZE 101
typedef struct //定义一个Queue的结构体 { int A[MAX_SIZE]; int front, rear; } Queue;
void init(Queue* q) { q->front = -1; q->rear = -1; }
int IsEmpty(Queue* q) { if (q->front == -1 && q->rear == -1) return 1; return 0; }
int IsFull(Queue* q) { if ((q->rear + 1) % MAX_SIZE == q->front) return 1; return 0; }
void enqueue(Queue* q, int x) { printf("入队元素:%d\n", x); if (IsFull(q)) { printf("队列已满,无法入队!\n"); return; } if (IsEmpty(q)) { q->front = q->rear = 0; } else { q->rear = (q->rear + 1) % MAX_SIZE; }
q->A[q->rear] = x; }
void dequeue(Queue* q) { printf("出队元素:\n"); if (IsEmpty(q)) { printf("队列为空,无法出队"); return; } else if (q->front == q->rear) { q->front = q->rear = -1; } else { q->front = (q->front + 1) % MAX_SIZE; } }
int front(Queue* q) { if (q->front == -1) { printf("错误:空队列无法返回队头元素\n"); return -1; } return q->A[q->front]; }
void printQueue(Queue* q) { int count = (q->rear + MAX_SIZE - q->front) % MAX_SIZE + 1; printf("队列:"); for (int i = 0; i < count; i++) { int index = (q->front + i) % MAX_SIZE; printf("%d", q ->A[index]); }
printf("\n\n"); } int main() { Queue q; init(&q); enqueue(&q, 2); printQueue(&q); enqueue(&q, 4); printQueue(&q); enqueue(&q, 6); printQueue(&q); dequeue(&q); printQueue(&q); enqueue(&q, 8); printQueue(&q); return 0; }
|