【问题描述】
栈的应用,利用递归与非递归方示编程实现输出字符金字塔
该回答引用GPTᴼᴾᴱᴺᴬᴵ
下面是使用递归和非递归方法实现输出字符金字塔的C++代码示例:
使用递归方法:
#include <iostream>
using namespace std;
// 输出n层字符金字塔
void printPyramid(int n, char ch) {
if (n <= 0) {
return;
}
// 输出n-1层字符金字塔
printPyramid(n-1, ch);
// 输出第n层
for (int i = 0; i < 2*n-1; i++) {
cout << ch;
}
cout << endl;
}
int main() {
int n = 4;
char ch = 'a';
printPyramid(n, ch);
return 0;
}
使用非递归方法:
#include <iostream>
#include <stack>
using namespace std;
// 输出n层字符金字塔
void printPyramid(int n, char ch) {
stack<int> s;
// 先输出空格
for (int i = n-1; i >= 0; i--) {
for (int j = 0; j < i; j++) {
cout << " ";
}
// 压入字符
for (int j = 0; j < 2*(n-i)-1; j++) {
s.push(ch);
}
// 依次输出栈中的字符
while (!s.empty()) {
cout << s.top();
s.pop();
}
cout << endl;
}
}
int main() {
int n = 4;
char ch = 'a';
printPyramid(n, ch);
return 0;
}
这里使用了一个栈来存储每一层的字符,先将字符压入栈中,然后依次输出栈中的字符,再换行输出下一层的字符。
有意思的题目。。。试试看,必须用栈?
以下是使用递归和非递归两种方式实现输出字符金字塔的C语言代码示例:
1. 使用递归方式实现输出字符金字塔:
#include <stdio.h>
// 递归函数,用于输出字符金字塔
void print_pyramid(int n, char c)
{
if (n <= 0) {
return;
}
print_pyramid(n - 1, c);
for (int i = 0; i < n; i++) {
printf("%c ", c);
}
printf("\n");
}
int main()
{
int n = 5; // 金字塔的高度
char c = '*'; // 金字塔使用的字符
// 输出字符金字塔
print_pyramid(n, c);
return 0;
}
2. 使用非递归方式实现输出字符金字塔:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int n = 5; // 金字塔的高度
char c = '*'; // 金字塔使用的字符
// 创建一个栈
char *stack = (char *)malloc(n * sizeof(char));
int top = -1;
// 循环输出字符金字塔
for (int i = 1; i <= n; i++) {
// 先将该行字符入栈
for (int j = 0; j < i; j++) {
stack[++top] = c;
}
// 逐个输出该行字符
for (int j = 0; j < i; j++) {
printf("%c ", stack[top--]);
}
printf("\n");
}
free(stack); // 释放栈内存
return 0;
}
这两种方法都可以实现字符金字塔的输出,具体实现方式略有不同。使用递归方法可以使代码更加简洁易懂,但可能会影响程序的效率;使用非递归方法需要手动维护一个栈来存储字符,代码稍微复杂一些,但效率可能更高
A
ABA
ABCBA
ABCDCBA
ABCDEDCBA
python
def print_pyramid_recursion(row, total_rows, chars):
if row == total_rows:
print(''.join(chars))
return
else:
chars[row] = chr(ord('A') + row)
for i in range(row - 1, -1, -1):
chars[i] = chars[i + 1]
print_pyramid_recursion(row + 1, total_rows, chars)
print(''.join(chars))
python
def print_pyramid_iteration(total_rows):
stack = []
for row in range(total_rows):
chars = [' '] * (2 * total_rows - 1)
for i in range(row + 1):
chars[total_rows - 1 - i] = chars[total_rows - 1 + i] = chr(ord('A') + i)
stack.append(chars)
while stack:
chars = stack.pop()
print(''.join(chars))