先说句题外话,用递归实现栈的翻转纯粹就是用来练习的,递归做的效率显然不是最好的。面试喜欢问这个问题目的也就是考察对递归的理解。
另外,不可能不用额外空间。递归就需要压栈,压栈就需要空间。
做法:
- 取出栈顶
- 翻转栈
- 把第1步取出的元素放到栈底
其中2,3两步就可以用递归做。
参考程序(可编译):
#include <iostream>
#include <stack>
using namespace std;
class ReverseStack {
public:
void reverseStackRecursively(stack& stk) {
if (stk.empty()) return;
reverse_stk(stk);
}
private:
void reverse_stk(stack& stk) {
if (stk.empty()) return;
int top_val = stk.top(); stk.pop();
reverse_stk(stk);
insert_to_bottom(stk, top_val);
}
void insert_to_bottom(stack& stk, int val) {
if (stk.empty()) {
stk.push(val);
return;
}
int top_val = stk.top(); stk.pop();
insert_to_bottom(stk, val);
stk.push(top_val);
}
};
int main()
{
stack stk;
for (int i = 5; i >= 1; i--) {
stk.push(i);
}
ReverseStack rs;
rs.reverseStackRecursively(stk);
while (!stk.empty()) {
cout << stk.top() << " ";
stk.pop();
}
}