【问题标题】:How to reverse print stack using recursion?如何使用递归反转打印堆栈?
【发布时间】:2016-09-27 05:11:52
【问题描述】:

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

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

我自己试过了,但结果不是我所期望的。我的代码看起来像这样。

#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;
}

有人介意指出我的错误吗?另外,当我通过引用传递堆栈时,结果出乎意料。感谢支持。

【问题讨论】:

  • 结果是什么,为什么不是你预期的?
  • 运行时错误是它向我展示的内容。在上面的实现中。感谢您的关注:) @fractalwrench
  • 我的算法正确打印反向堆栈吗?
  • stack&lt;T&gt; 旨在隐藏其实现。例如,您必须根据vector&lt;T&gt; 编写自己的堆栈。您收到错误是因为当您 pop 最后一个元素时,堆栈为空,然后您尝试打印不再存在的 st.top()。将cout 移到pop 之前。
  • 你当前的实现从上到下打印,stack&lt;T&gt; 不支持你想要的。您必须编写自己的 MyStack 类。此外,通过调用pop,您正在删除堆栈的顶部 - 您可能只想打印堆栈而不清空它。

标签: c++ recursion data-structures stack


【解决方案1】:

为什么不将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 }

【讨论】:

  • 为什么要存储top?
  • @behnc 因为如果你不这样做,它会在递归之前的 pop 之后丢失在以太中(这正是你的代码中的问题)。
  • @behnc,请参阅答案中的示例
  • 现在我明白了,先生。考虑反向打印链表。在链表的情况下,我们不需要存储任何数据,因为我们没有删除任何内容。但在堆栈的情况下,我们确实通过 pop 删除.所以在我们删除之前我们存储。我是对的先生吗? @WhozCraig
  • @behnc pop 就像它的名字所暗示的那样:从堆栈中弹出顶部元素。如果它是最后一个元素,则堆栈为空。之后,在空堆栈上调用top()(就像您的代码一样)会引发您的异常。 Mahedi 的描述既准确又值得选择。它详细描述了出了什么问题。
【解决方案2】:

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];
   }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-06-06
    • 2023-03-15
    • 2021-04-08
    • 1970-01-01
    • 1970-01-01
    • 2014-07-14
    • 2021-10-31
    • 2011-03-24
    相关资源
    最近更新 更多