如何使用递归反转打印堆栈
How to reverse print stack using recursion?
请注意,这只是反向打印而不是反转堆栈
我想做的是在递归的帮助下打印堆栈,即从下到上打印。
我已经尝试过自己,但结果不是我所期望的。我的代码如下所示。
#include <bits/stdc++.h>
using namespace std;
void print(stack<char>st){
if(st.empty()){return;}
st.pop();
print(st);
cout<<st.top();
}
int main() {
// Assume that I have stack already made....
print(st);
cout<<endl;
}
return 0;
}
有人介意指出我的错误吗?此外,当我通过引用传递堆栈时,结果是出乎意料的。感谢您的支持。
为什么不将st.top()
存储在变量中并稍后打印。
void print(stack<char>st)
{
if(st.empty())
{
return;
}
char top = st.top();
st.pop();
print(st);
cout<<top<<endl;
}
让我解释一下:-
假设,您的堆栈 --> 0, 1
在这里,调用层次结构
-
print({0, 1}) { // stack after pop -- {0} print({0}) }
-
print({0}) { // stack after pop -- {} print ({}) // here you want to print top of empty stack // which gives the exception }
pop 是函数获取元素以像反向一样打印
void printStack()
{
if(!isEmpty())
{
int temp = pop();
printStack();
printf(" %d ", temp);
push( temp);
}
}
int pop()
{
if (isEmpty())
printf("Stack is Empty...n");
else {
st.top = st.top - 1;
return st.array[st.top+1];
}
}
相关文章:
- C++打印堆栈
- 在 Linux 平台上以 C/C++ 打印进程的所有线程堆栈跟踪
- 我如何转换一个基于动态的,基于指针的int堆栈,以便将其打印成字符串
- 无法使用 OOP C++打印堆栈项
- 如何正确打印堆栈的向量
- 为什么谷歌测试不打印堆栈跟踪或文件名
- 在明夫中打印堆栈跟踪
- C++堆栈推送/打印实现
- 如何使用递归反转打印堆栈
- 尝试使用引脚工具从堆栈中打印寄存器的值
- 在 Windows 中的 MinGW 中打印堆栈跟踪
- 如何在C++中打印堆栈跟踪,并在C++中注入代码
- 为什么我可以打印动态分配的对象,但不能打印使用 cout <<在堆栈上创建的对象
- 打印堆栈所有元素的功能
- 打印堆栈的元素
- 正在从信号处理程序打印堆栈跟踪
- 打印堆栈函数
- 如何在c++中使用数组打印堆栈
- 如何在c++中打印堆栈
- Google日志不打印堆栈跟踪