编写一个程序实现顺序队列的各种基本运算(采用循环队列),并在此基础上设计一个主程序,完成如下功能:
- 初始化队列
- 入队
- 出队
- 判断队列是否为空
- 清空队列
- 销毁队列
- 获取队列长度
- 获取队头元素
- 遍历队列
//循环队列及操作的算法实现(front为队头元素的当前位置,rear为队尾元素的下一个位置) #include执行结果:#include #define INITSIZE 10 #define INCREMENT 5 typedef int ElemType; typedef struct { ElemType* data; int front; int rear; int QueueSize; } SqQueue; int InitQueue(SqQueue* Q) { Q->data = (ElemType*)malloc(INITSIZE * sizeof(ElemType)); if (!Q->data) return 0; Q->front = Q->rear = 0; Q->QueueSize = INITSIZE; return 1; //初始化成功则返回1 } void DestoryQueue(SqQueue* Q) { if (Q->data) free(Q->data); Q->data = NULL; Q->QueueSize = Q->front = Q->rear = 0; } void ClearQueue(SqQueue* Q) { Q->front = Q->rear = 0; } int QueueEmpty(SqQueue Q) { if (Q.front == Q.rear) return 1; //返回1代表为空队列,返回0代表不为空队列 else return 0; } int GetHead(SqQueue Q, ElemType* e) { if (Q.front == Q.rear) return 0; *e = Q.data[Q.front]; return 1; } int QueueLength(SqQueue Q) { return (Q.rear - Q.front + Q.QueueSize) % Q.QueueSize; } void QueueTraverse(SqQueue Q) { int i = Q.front; while (i != Q.rear) { printf("%d ", Q.data[i]); i = (i + 1) % Q.QueueSize; } printf("n"); } int EnQueue(SqQueue* Q, ElemType e) { if ((Q->rear + 1) % Q->QueueSize == Q->front) { Q->data = (ElemType*)realloc(Q->data, sizeof(ElemType) * (Q->QueueSize + INCREMENT)); Q->QueueSize += INCREMENT; } if (!Q->data) return 0; Q->data[Q->rear] = e; Q->rear = (Q->rear + 1) % Q->QueueSize; return 1; } int DeQueue(SqQueue* Q, ElemType* e) { if (Q->front == Q->rear) return 0; //队列为空则返回0,代表出队失败 *e = Q->data[Q->front]; Q->front = (Q->front + 1) % Q->QueueSize; return 1; } int main(void) { int i = 0, m = 0, k = 0, n = 0; ElemType d = 0; SqQueue Q; InitQueue(&Q); printf("输入队列元素个数:"); scanf("%d", &n); printf("执行入队操作:"); for (i = 0; i < n; i++) { EnQueue(&Q, i + 1); } printf("队列为:"); QueueTraverse(Q); printf("队列长度:%dn", QueueLength(Q)); k = QueueLength(Q); printf("连续%d次由队头删除元素,由队尾插入元素:n", k / 2); for (m = 1; m <= k / 2; m++) { DeQueue(&Q, &d); printf("删除的元素是%d,请输入要插入的元素:", d); scanf("%d", &d); EnQueue(&Q, d); } printf("新队列为:"); QueueTraverse(Q); n = GetHead(Q, &d); if (n) printf("队头元素的值:%dn", d); printf("清空队列n"); ClearQueue(&Q); printf("清空队列后,队列是否为空n=%d(1,为空;0,不为空)n", QueueEmpty(Q)); system("pause"); return 0; }



