直接上代码:
#include <iostream>
#include <cstdlib>
using namespace std;
typedef struct Node {
// 结点
int *data;
struct Node *next;
} Node;
typedef struct {
// 定义一个队列,包含头指针和尾指针
Node *front;
Node *rear;
} Queue;
int initQueue(Queue &Q) {
// 初始化队列,令头指针等于尾指针
Q.front = Q.rear = (Node *) malloc(sizeof(Node));
if (!Q.front)
exit(-2);
Q.front->next = nullptr;
return 0;
}
int enQueue(Queue &Q, int *e) {
// 插入元素e为Q的新的队尾元素
Node *p = (Node *) malloc(sizeof(Node));
if (!p)
exit(-2);
p->data = e;
p->next = nullptr;
Q.rear->next = p;
Q.rear = p;
return 1;
}
int deQueue(Queue &Q, int **e) {
// 若队列不空,则删除Q的队头元素,用e返回其值,并返回1;否则返回0
if (Q.front == Q.rear)
return 0;
Node *p = Q.front->next;
*e = p->data;
Q.front->next = p->next;
if (Q.rear == p)
Q.rear = Q.front;
free(p);
return 1;
}
void print_YangHui_Triangle(int n) {
Queue Q;
initQueue(Q);
for (int i = 1; i < n + 1; i++) {
int *arr = new int[i];
if (i == 1)
arr[0] = 1;
else {
for (int j = 1; j < i + 1; j++) {
if (j == 1 || j == i)
arr[j - 1] = 1;
else {
arr[j - 1] = Q.rear->data[j - 1] + Q.rear->data[j - 2];
}
}
}
enQueue(Q, arr);
}
for (int i = 1; i < n + 1; i++) {
int *arr;
deQueue(Q, &arr);
for (int j = 0; j < i; j++) {
cout << arr[j] << ' ';
}
cout << endl;
}
}
int main() {
print_YangHui_Triangle(3);
cout << endl;
print_YangHui_Triangle(5);
cout << endl;
print_YangHui_Triangle(10);
}
运行结果: