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
| #include <stdio.h> #define QueueSize 10 typedef char DataType; typedef struct SeqQueue { DataType queue[QueueSize]; int front, rear; int tag; } SeqQueue;
void InitQueue(SeqQueue *SQ)
{ SQ->front = SQ->rear = 0; } int QueueEmpty(SeqQueue SQ)
{ if (SQ.front == SQ.rear) return 1; else return 0; } int EnterQueue(SeqQueue *SQ, DataType e)
{ if (SQ->rear == QueueSize) return 0;
SQ->queue[SQ->rear] = e; SQ->rear = SQ->rear + 1; return 1; } int DeleteQueue(SeqQueue *SQ, DataType *e)
{ if (SQ->front == SQ->rear) return 0;
*e = SQ->queue[SQ->front]; SQ->front = SQ->front + 1; return 1; } void DisplayQueue(SeqQueue SQ)
{ if (QueueEmpty(SQ)) return;
if (SQ.front < SQ.rear) for (int i = SQ.front; i <= SQ.rear; i++) printf("%c", SQ.queue[i]); else for (int i = SQ.front; i <= SQ.rear + QueueSize; i++) printf("%c", SQ.queue[i % QueueSize]); printf("\n"); }
int ComputeCount(SeqQueue SQ) { int count = (SQ.rear - SQ.front + QueueSize) % QueueSize; return count; } int main() { SeqQueue Q; InitQueue(&Q); printf("A入队\n"); EnterQueue(&Q, 'A'); printf("B入队\n"); EnterQueue(&Q, 'B'); printf("C入队\n"); EnterQueue(&Q, 'C'); printf("队列中元素:"); DisplayQueue(Q); printf("队头元素第一次出队\n"); char e; DeleteQueue(&Q, &e); printf("出队的元素:"); printf("%c\n", e); printf("队头元素第二次出队\n"); DeleteQueue(&Q, &e); printf("出队的元素:"); printf("%c\n", e); printf("队列中元素:"); DisplayQueue(Q); printf("D入队\n"); EnterQueue(&Q, 'D'); printf("E入队\n"); EnterQueue(&Q, 'E'); printf("F入队\n"); EnterQueue(&Q, 'F'); printf("队列中元素:"); DisplayQueue(Q);
int a[] = {34, 3, 56, 43, 21, 51, 46, 89, 98, 76}; InitQueue(&Q); for (int i = 0; i < 10; i++) EnterQueue(&Q, a[i]); printf("队列中的元素个数是:%2d\n", ComputeCount(Q)); printf("出队列的元素依次是:"); for (int i = 0; i < 10; i++) { DeleteQueue(&Q, &e); printf("%4d", e); } printf("\n清空队列后,队列中的元素个数是:%2d\n", ComputeCount(Q));
return 0; }
|