算法思路:
- 先将栈中的元素递归到底并保存到函数调用栈中;
- 将元素从函数调用栈依次取出并返回到栈中。
代码实现:
void insertAtBottom(stack &s, int x) {
if(s.empty()) {
s.push(x);
return;
}
int val = s.top();
s.pop();
insertAtBottom(s, x);
s.push(val);
}
void reverseStack(stack &s) {
if(s.empty()) {
return;
}
int val = s.top();
s.pop();
reverseStack(s);
insertAtBottom(s, val);
}
示例:
堆栈元素:1 2 3 4 5
堆栈翻转后:5 4 3 2 1
再调用reverseStack函数后,元素按照原始顺序返回到栈中:1 2 3 4 5。