用队列写杨辉三角c++
时间: 2023-07-01 17:14:15 浏览: 84
好的,以下是用队列写杨辉三角的 C++ 代码:
```c++
#include <iostream>
#include <queue>
using namespace std;
void PascalTriangle(int n) {
queue<int> q;
q.push(1); // 第一行只有一个数 1
for (int i = 1; i <= n; i++) {
int pre = 0; // 上一行的数
for (int j = 0; j < i; j++) {
int cur = q.front(); // 当前数
q.pop();
cout << cur << " "; // 输出当前数
q.push(pre + cur); // 计算下一行的数并加入队列
pre = cur; // 更新上一行的数
}
q.push(1); // 每行最后一个数也是 1
cout << endl;
}
}
int main() {
int n;
cout << "请输入要输出的行数:";
cin >> n;
PascalTriangle(n);
return 0;
}
```
运行程序后,根据提示输入要输出的行数,即可输出相应行数的杨辉三角。
相关问题
队列打印杨辉三角c++
队列打印杨辉三角是一种常见的算法问题,可以使用队列来实现。下面是使用C++语言实现队列打印杨辉三角的代码:
```cpp
#include <iostream>
#include <queue>
void printYanghuiTriangle(int n) {
std::queue<int> q;
q.push(1); // 第一行的元素1入队
for (int i = 0; i < n; i++) {
int prev = 0; // 上一行的元素初始为0
// 打印空格
for (int j = 0; j < n - i - 1; j++) {
std::cout << " ";
}
// 打印当前行的元素
for (int j = 0; j <= i; j++) {
int curr = q.front();
q.pop();
std::cout << curr << " ";
// 计算下一行的元素并入队
int next = prev + curr;
q.push(next);
prev = curr;
}
std::cout << std::endl;
}
}
int main() {
int n;
std::cout << "请输入要打印的杨辉三角的行数:";
std::cin >> n;
printYanghuiTriangle(n);
return 0;
}
```
运行以上代码,输入要打印的杨辉三角的行数,即可输出相应行数的杨辉三角。
循环队列实现杨辉三角C++
循环队列实现杨辉三角的C++代码如下:
```c++
#include <iostream>
using namespace std;
const int MAXN = 100;
int q[MAXN];
int front = 0, rear = 0;
void enqueue(int x) {
q[rear] = x;
rear = (rear + 1) % MAXN;
}
int dequeue() {
int x = q[front];
front = (front + 1) % MAXN;
return x;
}
int main() {
int n;
cout << "请输入杨辉三角的行数:";
cin >> n;
enqueue(1);
for (int i = 1; i <= n; i++) {
int last = 0;
for (int j = 0; j < i; j++) {
int x = dequeue();
cout << x << " ";
enqueue(x + last);
last = x;
}
cout << endl;
enqueue(1);
}
return 0;
}
```
阅读全文
相关推荐
![doc](https://img-home.csdnimg.cn/images/20241231044833.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![txt](https://img-home.csdnimg.cn/images/20241231045021.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![txt](https://img-home.csdnimg.cn/images/20241231045021.png)
![-](https://img-home.csdnimg.cn/images/20241231044937.png)
![-](https://img-home.csdnimg.cn/images/20241231045021.png)