如何使用递归反转打印堆栈

How to reverse print stack using recursion?

本文关键字:打印 堆栈 何使用 递归      更新时间:2023-10-16

请注意,这只是反向打印而不是反转堆栈

我想做的是在递归的帮助下打印堆栈,即从下到上打印。

我已经尝试过自己,但结果不是我所期望的。我的代码如下所示。

#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

在这里,调用层次结构

  1. print({0, 1}) { // stack after pop -- {0} print({0}) }
  2. 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];
   }
}