step: 1)先将栈底的元素拿出来, ff( )函数实现
2)再将剩下的反转,reverse()函数实现
3)依次递归调用
代码:
#include<iostream>
#include<stack>
using namespace std;
//用递归反转栈,不用其他数据结构
int ff(stack<int>& s);
void reverse(stack<int> &s) {
if (s.empty())
return;
int i = ff(s);//拿到栈底的元素
reverse(s);
s.push(i);//再将栈底元素放进栈顶
}
int ff(stack<int>& s) {
int result = s.top();
s.pop();
if (s.empty())
return result;
else {
int last = ff(s);
s.push(result);
return last;
}
}
int main() {
stack<int> s;
s.push(1);
s.push(2);
s.push(3);
s.push(4);
reverse(s);
while (!s.empty()) {
cout << s.top() << " ";
s.pop();
}
}
递归过程讲解:
(黄色笔是调用过程从上到下,红色笔是返回递归过程从下到上)