使用递归
#include <iostream>
#include <stack>
using namespace std;
int getDownItem(stack<int>& s);
void rStack(stack<int>& s);
void printStack(stack<int> s)
{
if (s.empty()){
return;
}
cout << s.top() << endl;
s.pop();
printStack(s);
}
void test()
{
stack<int> mys;
mys.push(4);
mys.push(3);
mys.push(2);
mys.push(1);
printStack(mys);
cout << "逆序之后" << endl;
rStack(mys);
printStack(mys);
}
int getDownItem(stack<int>& s)
{
int result = s.top();
s.pop();
if (s.empty()) {
return result;
}
int last = getDownItem(s);
s.push(result);
return last;
}
void rStack(stack<int>& s)
{
if (s.empty()) {
return;
}
int ret = getDownItem(s);
rStack(s);
s.push(ret);
}
int main()
{
test();
cout << "hello world!" << endl;
system("pause");
return 0;
}
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/57ecd95c6310e8d09b022ff2c4fca86b.png)