1 #include <stdio.h> 2 #include <stdlib.h> 3 4 typedef char DataType; 5 6 #define QueueSize 40 7 8 typedef struct { 9 DataType data[QueueSize]; 10 //定义队列的头部、尾部,像排队打饭一样,从尾巴rear进,从front头部出 11 int front, rear; 12 }SqQueue; 13 14 //初始化队列 15 void InitQueue(SqQueue &Q) 16 { 17 Q.rear = Q.front = 0; 18 } 19 20 //判断队列是否为空 21 bool QueueEmpty(SqQueue Q) 22 { 23 if (Q.front == Q.rear) 24 { 25 return true; 26 } 27 else 28 { 29 return false; 30 } 31 } 32 33 //入队操作 34 bool EnterQueue(SqQueue &Q, DataType x) 35 { 36 //判断队列是否已满 37 if (Q.rear == QueueSize - 1) 38 { 39 return false; 40 } 41 else 42 { 43 Q.data[Q.rear] = x; 44 Q.rear += 1;//队尾指针向后移动一个位置 45 return true; 46 } 47 } 48 49 //出队操作 50 bool DeleteQueue(SqQueue &Q, DataType &x) 51 { 52 //出队删除时先判断队空 53 if (Q.front==Q.rear) 54 { 55 return false; 56 } 57 else 58 { 59 x = Q.data[Q.front]; 60 Q.front += 1; 61 return true; 62 } 63 } 64 65 int main() 66 { 67 char str[] = "ABCDEFGH"; 68 char x; 69 70 SqQueue Q; 71 InitQueue(Q); 72 73 74 for (int i = 0; i < sizeof(str) - 1; i++) 75 { 76 //将字符串中的数据插入队列 77 EnterQueue(Q, str[i]); 78 } 79 80 DeleteQueue(Q, x); 81 printf("出队列的元素为:%c\n", x); 82 83 printf("顺序队列中的元素为:"); 84 //判断是否队列不为空 85 if (QueueEmpty(Q) == false) 86 { 87 //这里循环时要注意用队列的头和尾进行循环 88 for (int i = Q.front; i < Q.rear; i++) 89 { 90 printf("%c", Q.data[i]); 91 } 92 } 93 94 95 96 97 getchar(); 98 return 0; 99 }
原文:https://www.cnblogs.com/imxiaodi/p/13785291.html