Data Structure Stack: Reverse a stack using recursion

时间:2022-06-15 16:01:37

http://www.geeksforgeeks.org/reverse-a-stack-using-recursion/

 #include <iostream>
#include <vector>
#include <algorithm>
#include <queue>
#include <stack>
#include <string>
#include <fstream>
#include <map>
#include <set>
using namespace std; void insertbottom(stack<int> &S, int top) {
if (S.empty()) S.push(top);
else {
int tmp = S.top();
S.pop();
insertbottom(S, top);
S.push(tmp);
}
} void reversestack(stack<int> &S) {
if (S.empty()) return;
int top = S.top();
S.pop();
reversestack(S);
insertbottom(S, top);
} int main() {
stack<int> S;
S.push();
S.push();
S.push();
S.push();
reversestack(S);
while (!S.empty()) {
cout << S.top() << endl;
S.pop();
}
return ;
}