Java数据结构用队列实现杨辉三角形打印
时间: 2024-12-19 11:19:25 浏览: 44
在Java中,我们可以使用队列(Queue)数据结构来实现杨辉三角形的打印。杨辉三角是一个数组型的数据结构,每一行都是前一行的数加当前行序号的组合,从0开始。队列可以用来存储当前需要打印的数字及其位置。
以下是使用递归和队列实现杨辉三角的一种方法:
```java
import java.util.LinkedList;
import java.util.Queue;
public class YangHuiTriangle {
public static void print(int n) {
Queue<int[]> queue = new LinkedList<>();
// 初始化队列,第一行只有一个元素 [1]
if (n > 0) {
int[] row = {1};
queue.offer(row);
}
while (!queue.isEmpty()) {
int[] currentRow = queue.poll();
System.out.println(currentRow);
// 如果还有剩余行需要打印
if (currentRow.length > 1) {
for (int i = 1; i < currentRow.length - 1; i++) {
// 构造下一行并添加到队列
int[] nextRow = new int[currentRow.length];
nextRow[0] = currentRow[0];
nextRow[i + 1] = currentRow[i];
nextRow[i] = currentRow[i - 1] + currentRow[i]; // 加上上方两个数
queue.offer(nextRow);
}
}
}
}
public static void main(String[] args) {
int n = 5; // 想打印的行数
print(n);
}
}
```
在这个例子中,我们首先创建一个队列,并放入首行 [1]。然后进入一个循环,在每次迭代中,我们从队列中取出一行,打印它,然后构造下一行并将其加入队列。这个过程会一直持续到队列为空,即所有行都已打印完毕。
阅读全文
相关推荐















