C语言实现设从键盘输入一整数序列a1,a2,…an,试编程实现:当ai>0时,ai进队,当ai<0时,将队首元素出队,当ai=0时,表示输入结束。要求将队列处理成环形队列,使用环形队列算法库中定义的数据类型及算法,程序中只包括一个函数(main函数),入队和出队等操作直接在main函数中调用即可。当进队出队异常(如队满)时,要打印出错信息
时间: 2023-06-05 17:06:10 浏览: 314
这个问题是技术问题,我可以回答。以下是C语言实现环形队列算法的代码:
```
#include <stdio.h>
#include <stdlib.h>
#define MAXSIZE 10
typedef struct{
int data[MAXSIZE]; // 环形队列数组
int front; // 队首指针
int rear; // 队尾指针
} CircleQueue;
void InitQueue(CircleQueue *queue){
queue->front = queue->rear = 0;
}
int EnQueue(CircleQueue *queue, int x){
if((queue->rear + 1) % MAXSIZE == queue->front){ // 队列已满
printf("队列已满,无法继续进队!\n");
return 0;
} else {
queue->rear = (queue->rear + 1) % MAXSIZE;
queue->data[queue->rear] = x;
return 1;
}
}
int DeQueue(CircleQueue *queue, int *x){
if(queue->rear == queue->front){ // 队列为空
printf("队列已空,无法继续出队!\n");
return 0;
} else {
queue->front = (queue->front + 1) % MAXSIZE;
*x = queue->data[queue->front];
return 1;
}
}
int main(){
int a, x;
CircleQueue queue;
InitQueue(&queue);
do{
scanf("%d", &a);
if(a > 0){
if(!EnQueue(&queue, a)){
return 0;
}
} else if(a < 0){
if(!DeQueue(&queue, &x)){
return 0;
}
}
} while(a != 0);
return 0;
}
```