如何在 c++ 中将内置堆栈作为对递归函数的引用传递

How to pass Inbuilt stack as reference to a recursive function in c++

本文关键字:递归函数 引用 堆栈 c++ 内置      更新时间:2023-10-16

我必须递归地反转堆栈。使用相同的堆栈。

void reverse(stack<int> *s)
{
  if(s->empty())
    return;
 int element= s->top();
  s->pop();
  reverse(s);
  s->push(element);
}

我不确定 LIFO 结构是否可能,在您的代码中,您从顶部删除一个然后将其放在顶部,没有意义,可以使用数组或其他堆栈作为参数。为了将某些东西放在第一个位置堆栈上,需要为空,或者您可以实现方法 PushAtBottom,但我想它不再是堆栈,您将需要使用自己的堆栈。

例:

#include<iostream>
template<class s>
class stack
{
        int top;
        s* Array;
        int counter;
public:
    stack(){
        top = 0;
        Array = new s[10];
        counter = 0;
    }
    s Pop(){
        if(top!=0){
            s rTop = Array[top];
            Array[top] = NULL;
            top--;
            return rTop;
        }
        return NULL;
    }
    void Push(s item){
        top++;
        Array[top] = item;
    }
    void PushAtBottom(s item){
        for(int i=top;i>counter;i--)
        {
            Array[i+1] = Array[i]; 
        }
        Array[++counter] = item;
        top++;
    }
    bool empty(){
        if(top!=0)
            return false;
        return true;
    }
    bool reverse_done(){ //funtion that stops recursion
        if(counter >= top)
            return true;
        return false;
    }
};
void stack_reverse(stack<int> *s){
    if(s->reverse_done())
        return;
    s->PushAtBottom(s->Pop());
    stack_reverse(s);
}
void main(){
    stack<int> * s = new stack<int>();
    s->Push(1);
    s->Push(2);
    s->Push(3);
    stack_reverse(s);
    std::cout << s->Pop();
    std::cout << s->Pop();
    std::cout << s->Pop();
}