问题:
用递归颠倒一个栈。例如输入栈{1, 2, 3, 4, 5},1在栈顶。颠倒之后的栈为{5, 4, 3, 2, 1},5处在栈顶。
分析:
问题很简单,可以直接使用两个堆栈就行,一个pop,一个push,这样就颠倒了,但是如果加强问题,不能使用另一个栈,我们可以考虑使用递归调用(实际上递归调用也用到了栈,只是在程序调用时用到的)。程序执行分为两部分:1,reverse_stack,从栈顶弹出一个元素,然后递归调用reverse_stack,再将弹出的元素添加到最下面
2,addToBottom,将栈顶弹出,然后递归调用addToBottom,直到栈为空,然后将bottom元素push到栈
算法代码:
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <vector>
using namespace std;
void addToBottom(vector<int> &stack, int bottom)
{
if (stack.empty())
stack.push_back(bottom);
else
{
int top = stack.back();
stack.pop_back();
addToBottom(stack, bottom);
stack.push_back(top);
}
return;
}
void reverse_stack(vector<int> &stack)
{
if (stack.empty())
return;
int top = stack.back();
stack.pop_back();
reverse_stack(stack);
addToBottom(stack, top);
return;
}
int main()
{
vector<int> array;
for (int i = 0; i < 5; i++)
array.push_back(i);
reverse_stack(array);
int num;
for (int i = 0; i < 5; i++)
{
num = array.back();
array.pop_back();
cout << num << endl;
}
return 0;
总结:
通过这个题目,可以更加深刻地了解递归的真谛,还是不错的一个题目。