代码:
利用递归暂时保存栈顶元素。其他见注释
//利用递归得到栈底元素,并将栈底元素弹出
int getbottom(stack<int> &s) {
int top = s.top();
s.pop();
if (s.empty())
return top;
int next = getbottom(s);
//不是栈底元素的时候要把当前元素入栈
s.push(top);
return next;
}
void reveser_stack(stack<int> &s) {
if (s.empty())
return;
int bottom = getbottom(s);
reveser_stack(s);
s.push(bottom);
}
int main() {
stack<int>s;
for (int i = 1; i <= 5; i++)
s.push(i);
reveser_stack(s);
//while (!s.empty()) {
// cout << s.top() << endl;;
// s.pop();
//}
return 0;
}