队列的顺序存储实现
1 #include <stdio.h> 2 #include <stdlib.h> 3 #include <time.h> 4 5 typedef int ElemType; 6 #define OK 1 7 #define ERROR 0 8 typedef int Status; 9 #define MAXSIZE 100 10 11 typedef struct 12 { 13 ElemType data[MAXSIZE]; 14 int front, rear; 15 }SqQueue; 16 17 Status InitQueue(SqQueue *Q) 18 { 19 Q->front = 0; 20 Q->rear = 0; 21 return OK; 22 } 23 int QueueLength(SqQueue Q) 24 { 25 return (Q.rear - Q.front + MAXSIZE) % MAXSIZE; 26 } 27 Status EnQueue(SqQueue *Q,ElemType e) 28 { 29 if ((Q->rear+1)%MAXSIZE ==Q->front) 30 return ERROR; 31 Q->data[Q->rear] = e; 32 Q->rear = (Q->rear + 1) % MAXSIZE; 33 return OK; 34 } 35 Status DeQueue(SqQueue *Q,ElemType *e) 36 { 37 if (Q->front == Q->rear) 38 return ERROR; 39 *e = Q->data[Q->front]; 40 Q->front = (Q->front + 1) % MAXSIZE; 41 return OK; 42 } 43 void visit(ElemType n) 44 { 45 printf("%d ", n); 46 } 47 48 void ListTraverse(SqQueue Q) 49 { 50 while(Q.front != Q.rear) 51 { 52 visit(Q.data[Q.front]); 53 Q.front = (Q.front + 1) % MAXSIZE; 54 } 55 } 56 int main() 57 { 58 SqQueue L; 59 Status i, j; 60 char opp = '-1'; 61 ElemType e; 62 int pos = 1; 63 int k = 0; 64 65 i = InitQueue(&L); 66 printf("队列L初始化完毕,StackLength(L)=%d\n\n", QueueLength(L)); 67 68 printf("\n1.遍历操作 \n2.插入操作 \n3.删除操作 \n0.退出 \n请选择你的操作:\n"); 69 70 while (opp != '0') { 71 scanf_s("%c", &opp); 72 switch (opp) { 73 case '1': 74 ListTraverse(L); 75 printf("\n"); 76 break; 77 78 case '2': 79 srand((unsigned)time(NULL)); 80 for (j = 1; j <= 10; j++) 81 { 82 i =EnQueue(&L, rand() % 100); 83 } 84 printf("在队列中依次插入10个随机数后:"); 85 ListTraverse(L); 86 printf("\n"); 87 printf("创建完毕,QueueLength(L)=%d\n\n", QueueLength(L)); 88 break; 89 case '3': 90 e = -1; 91 DeQueue(&L, &e); 92 printf("弹出队列投元素%d,现在链表为:\n", e); 93 ListTraverse(L); 94 printf("\n"); 95 break; 96 97 case '0': 98 exit(0); 99 } 100 } 101 }