C++使用链式储存结构打印杨辉三角
时间: 2024-06-06 19:07:33 浏览: 27
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int data;
struct Node *next;
} Node;
void print_yanghui_triangle(int n) {
Node *pre_head, *cur_head, *p, *q;
pre_head = (Node *) malloc(sizeof(Node));
cur_head = (Node *) malloc(sizeof(Node));
pre_head->next = NULL;
cur_head->next = NULL;
for (int i = 1; i <= n; i++) {
// 打印空格
for (int j = 1; j <= n - i; j++) {
printf(" ");
}
// 生成当前行的链表
cur_head->data = 1;
cur_head->next = NULL;
p = cur_head;
for (int j = 2; j <= i; j++) {
q = (Node *) malloc(sizeof(Node));
q->data = p->data * (i - j + 1) / j;
q->next = NULL;
p->next = q;
p = q;
}
// 打印当前行的链表
p = cur_head;
while (p != NULL) {
printf("%d ", p->data);
p = p->next;
}
printf("\n");
// 交换前一行和当前行的链表
p = pre_head->next;
pre_head->next = cur_head;
cur_head = p;
}
// 释放链表内存
p = pre_head;
while (p != NULL) {
q = p;
p = p->next;
free(q);
}
}
int main() {
int n;
printf("请输入杨辉三角的行数:");
scanf("%d", &n);
print_yanghui_triangle(n);
return 0;
}
阅读全文