递归地搜索堆栈,但保持堆栈完整

Search a stack recursively, but leave the stack intact

本文关键字:堆栈 搜索 递归      更新时间:2023-10-16

我一直在尝试编写一个递归函数,它搜索堆栈,但使堆栈保持其原始状态。我可能会想H和pop堆栈,但不使用helper堆栈或任何其他数据结构。

是的,这是家庭作业,所以我不期望一个完整的编码答案:)。如果能提供一点关于如何接近堆栈的帮助,以便在递归搜索完成后堆栈是完整的,我将不胜感激。

在堆栈中搜索指定项(但破坏堆栈)的递归函数如下:

template <class Type>
Type getNth(stack(Type) & s, int n)
{
    if(s.empty())
        return -1;
    if(s.top() == n)
        return s.top();
    if(s.top() != n && s.empty())
        return -1;
    else
        s.pop();
        return getNth(s, n);
}
到目前为止,这是可行的。如有任何帮助,不胜感激

在返回之前,应存储pop()的ed值和递归调用的结果,并将push()的ed值存储回pop()

你的else应该看起来像这样:[other than it, it looks fine]

else
    temp = s.pop();
    retVal =  getNth(s, n);
    s.push(temp);
    return retVal;

(*)请原谅我没有声明tempretVal,你可以从这里理解大意…


编辑:
我决定添加一个简单的例子,假设你的堆栈是

|1|
|2|
|3|
|4|
---

,然后调用getth (s,3),这就是栈发生的情况
after 1st pop() and getNth(): [stop condition is not reached, so keep going]

|2|
|3|
|4|
---

2nd pop(),getNth(): [again, keep go]

|3|
|4|
---

现在,当您检查s.p op() == n时,您就会意识到它们是!所以返回n。当从递归返回时,调用s.push(temp)temp==2,所以我们得到:

|2|
|3|
|4|
---

,我们再次返回retVal,现在从递归返回,我们再次使用s.push(),我们得到:

|1|
|2|
|3|
|4|
---

原来的栈!并返回与递归返回的相同的returnVal !


注意:这不是你的问题,但是函数的名称暗示你不想返回你正在搜索的值,而是堆栈中的第n个元素,这意味着,如果你的堆栈是:

|5|
|8|
|8|
|8|
|2|
|4|
---

getNth(2)需要返回8,而不是2,正如你的问题所描述的那样。
但是我不可能肯定地知道,如果是这样的话,我认为你有足够的工具来处理这个问题,没有太多的问题!

祝你好运!


编辑2:
在评论中的讨论之后,很明显OP想要一些与原始问题描述的有点不同的东西,因此额外的编辑:

你的解决方案是搜索一个元素并返回它,可能你想做的是计数直到这些元素,然后返回,应该是这样的[再次,不声明所有变量,它不会编译,它只是一个方向]:

template <class Type>
Type getNth(stack(Type) & s, int n)
{
    if(s.empty()) {return -1; } //note that in C++ throwing an exception here will be more wise, since -1 might be not matching to Type
    else if(n == 0) { return s.top(); }
    else {
        temp = s.pop();
        retVal = getNth(s, n-1);
        s.push(temp);
        return retVal;
   }
}