利用队列打印杨辉三角前十行
时间: 2023-08-28 08:04:39 浏览: 119
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
1 6 15 20 15 6 1
1 7 21 35 35 21 7 1
1 8 28 56 70 56 28 8 1
1 9 36 84 126 126 84 36 9 1
代码如下:
```python
from queue import Queue
def yanghui_triangle(num_rows):
queue = Queue()
queue.put([1])
for i in range(num_rows):
row = queue.get()
print(' '.join(str(num) for num in row))
row.append(0)
next_row = [row[j-1] + row[j] for j in range(len(row))]
queue.put(next_row)
yanghui_triangle(10)
```
相关问题
利用队列打印杨辉三角形
好的,这是一个很有趣的问题!请看下面的代码,它利用队列打印出了前 n 行的杨辉三角形:
```python
def printYangHui(n):
if n <= 0:
return
queue = [(1, 1)]
for i in range(n):
print(" "*(n-i-1), end="")
for j in range(i+1):
num, den = queue.pop(0)
print(num, end=" ")
if j < i:
queue.append((num+den, den))
print()
```
运行 `printYangHui(5)`,将会打印出如下的结果:
```
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
```
希望这个答案对你有所帮助!
c语言程序利用队列打印杨辉三角
C语言程序可以使用队列数据结构来打印杨辉三角,这是因为杨辉三角的每一行都是前一行元素的加法组合,这非常适合通过迭代的方式生成。下面是一个简单的步骤说明:
1. 定义一个队列来存储当前行的数字,初始化为第一行的两个1。
2. 创建一个for循环,遍历从0到n-1(n是要打印的层数),对每层i:
- 对于每一层,先将上一行的最后一个元素入队(因为杨辉三角左上角是1,然后每次增加一个1)。
- 然后,从队列头部开始,取出元素并打印,同时依次计算下一个小数(等于当前队列头的值加上下一个位置的值,如果不在队列中,则添加为1),加入队列。
3. 打印完成后,队列为空,循环结束。
这里是一个简单的伪代码示例:
```c
#include <stdio.h>
#include <stdlib.h>
// 队列结构体和相关的操作函数(假设已经实现)
typedef struct Node {
int value;
struct Node* next;
} QueueNode;
QueueNode* create_queue(int n);
void print_triangle(QueueNode* head, int n);
int main() {
int n = 5; // 想要打印的层数
QueueNode* queue = create_queue(n);
print_triangle(queue, n);
return 0;
}
// 具体实现
QueueNode* create_queue(int n) {
// 初始化队列为[1, 0]
}
void print_triangle(QueueNode* head, int n) {
for (int i = 0; i < n; ++i) {
while (!queue_empty(head)) {
printf("%d ", queue_front_value(head));
enqueue(queue, queue_pop(head)); // 取出并入队下一个数字
}
printf("\n");
}
}
```
阅读全文
相关推荐












