问题描述:
一个栈依次压入1,2,3,4,5那么从栈顶到栈底分别为5,4,3,2,1。将这个栈转置后,从栈顶到栈底为1,2,3,4,5,也就是实现栈中元素的逆序,但是只能用递归函数来实现,而不能用另外的数据结构。
实现代码:
#include <stack>
#include <stdio.h>
using namespace std;
int GetAndRemoveBottom(stack<int> &ss)
{
int top, bottom;
top = ss.top();
ss.pop();
if(ss.empty())
return top;
bottom = GetAndRemoveBottom(ss);
ss.push(top);
return bottom;
}
void ReverseStack(stack<int> &ss)
{
if(ss.empty()) return ;
int bottom = GetAndRemoveBottom(ss);
ReverseStack(ss);
ss.push(bottom);
}
int main()
{
stack<int> ss;
for(int i = 1; i <= 5; i++)
ss.push(i);
ReverseStack(ss);
while(!ss.empty())
{
printf("%d ", ss.top());
ss.pop();
}
}
来源:https://www.cnblogs.com/1203ljh/p/4736166.html