如何在 c++ 中将内置堆栈作为对递归函数的引用传递
How to pass Inbuilt stack as reference to a recursive function in c++
我必须递归地反转堆栈。使用相同的堆栈。
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();
}
相关文章:
- 递归函数计算序列中的平方和(并输出过程)
- 如何在Elixir中调用递归函数并行
- 递归函数有效,但无法记忆
- 为什么我的递归函数按降序打印,然后按升序打印?
- 为什么递归函数的最终输出是 5?
- 有没有办法使用递归函数找到数组中最小值的 INDEX?C++
- 如何将记忆应用于此递归函数?
- 如何从递归函数中完全返回,该函数给出了每个函数结果的累积相加?
- 无穷大而循环时具有递归函数
- 即使没有调用这个递归函数,它是如何工作的?
- 如何使此递归函数从给定的起始位置返回最小的整数?
- 此递归函数的每次迭代的值存储在哪里?
- C++ 引用类型作为递归函数参数
- 如何在递归函数中调用引用数组?
- 静态短引用在递归函数中产生错误
- 如何在 c++ 中将内置堆栈作为对递归函数的引用传递
- 通过引用传递递归函数
- 传递一个向量作为递归函数的引用
- 在递归函数中通过引用传递的数组 - 最后一列重新初始化
- 通过引用递归函数传递字符串或流对象时出现的段错误