用C语言队列法求斐波那契数列前20项
时间: 2023-08-04 08:33:11 浏览: 49
好的,以下是使用C语言队列法求解斐波那契数列前20项的示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
#define MAX 20
typedef struct queue {
int data[MAX];
int head;
int tail;
} Queue;
void init(Queue* q)
{
q->head = 0;
q->tail = 0;
}
int empty(Queue* q)
{
return q->head == q->tail;
}
int full(Queue* q)
{
return (q->tail + 1) % MAX == q->head;
}
void push(Queue* q, int x)
{
if (full(q))
{
printf("Queue is full!\n");
return;
}
q->data[q->tail] = x;
q->tail = (q->tail + 1) % MAX;
}
int pop(Queue* q)
{
if (empty(q))
{
printf("Queue is empty!\n");
return -1;
}
int x = q->data[q->head];
q->head = (q->head + 1) % MAX;
return x;
}
int main()
{
Queue q;
init(&q);
int a = 0, b = 1;
push(&q, a);
push(&q, b);
for (int i = 2; i < MAX; i++)
{
int c = a + b;
push(&q, c);
a = b;
b = c;
}
while (!empty(&q))
{
printf("%d ", pop(&q));
}
return 0;
}
```
在上面的代码中,我们使用一个定长循环队列来存储斐波那契数列的前两项,然后依次计算后面的项并将它们加入队列中。最后,我们输出队列中的前20项即可。