建立长为n的循环队列,依次讲m个数据入列,k次出列操作,再将j个数据入列后,从头输出
时间: 2024-05-12 12:17:36 浏览: 73
建立长为n的循环队列的代码如下:
```c
typedef struct{
int *data;
int front, rear;
}Queue;
void init(Queue *q, int n){
q->data = (int *)malloc(sizeof(int) * n);
q->front = q->rear = 0;
}
void enqueue(Queue *q, int x){
if((q->rear + 1) % n == q->front){
printf("Queue is full\n");
return;
}
q->data[q->rear] = x;
q->rear = (q->rear + 1) % n;
}
int dequeue(Queue *q){
if(q->front == q->rear){
printf("Queue is empty\n");
return -1;
}
int res = q->data[q->front];
q->front = (q->front + 1) % n;
return res;
}
```
依次将m个数据入列:
```c
for(int i = 1; i <= m; ++i){
int x;
scanf("%d", &x);
enqueue(q, x);
}
```
进行k次出列操作:
```c
for(int i = 1; i <= k; ++i){
dequeue(q);
}
```
将j个数据入列:
```c
for(int i = 1; i <= j; ++i){
int x;
scanf("%d", &x);
enqueue(q, x);
}
```
从头输出:
```c
int p = q->front;
while(p != q->rear){
printf("%d ", q->data[p]);
p = (p + 1) % n;
}
printf("\n");
```
笑话:
为什么程序员总是把十进制看成二进制? 因为他们总是把高位看成了低位!
阅读全文