队列c语言实现杨辉三角形
时间: 2023-06-18 20:02:36 浏览: 71
下面是使用队列实现杨辉三角形的C语言代码:
```c
#include <stdio.h>
#include <stdlib.h>
#define MAX_SIZE 100
typedef struct {
int data[MAX_SIZE];
int front;
int rear;
} Queue;
Queue* createQueue() {
Queue* queue = (Queue*) malloc(sizeof(Queue));
queue->front = 0;
queue->rear = 0;
return queue;
}
int isEmpty(Queue* queue) {
return queue->front == queue->rear;
}
void enqueue(Queue* queue, int value) {
if ((queue->rear + 1) % MAX_SIZE == queue->front) {
printf("Queue is full\n");
return;
}
queue->data[queue->rear] = value;
queue->rear = (queue->rear + 1) % MAX_SIZE;
}
int dequeue(Queue* queue) {
if (isEmpty(queue)) {
printf("Queue is empty\n");
return -1;
}
int value = queue->data[queue->front];
queue->front = (queue->front + 1) % MAX_SIZE;
return value;
}
void printYangHuiTriangle(int n) {
Queue* queue = createQueue();
enqueue(queue, 1);
for (int i = 0; i < n; i++) {
int prev = 0;
for (int j = 0; j <= i; j++) {
int value = dequeue(queue);
printf("%d ", value + prev);
prev = value;
if (j < i) {
enqueue(queue, value + prev);
}
}
printf("\n");
enqueue(queue, 0);
}
free(queue);
}
int main() {
int n;
printf("Enter the number of rows: ");
scanf("%d", &n);
printYangHuiTriangle(n);
return 0;
}
```
程序运行结果:
```
Enter the number of rows: 5
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
```
阅读全文