Data Structure Stack: Reverse a stack using recursion

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

 1 #include <iostream>

 2 #include <vector>

 3 #include <algorithm>

 4 #include <queue>

 5 #include <stack>

 6 #include <string>

 7 #include <fstream>

 8 #include <map>

 9 #include <set>

10 using namespace std;

11 

12 void insertbottom(stack<int> &S, int top) {

13     if (S.empty()) S.push(top);

14     else {

15         int tmp = S.top();

16         S.pop();

17         insertbottom(S, top);

18         S.push(tmp);

19     }

20 }

21 

22 void reversestack(stack<int> &S) {

23     if (S.empty()) return;

24     int top = S.top();

25     S.pop();

26     reversestack(S);

27     insertbottom(S, top);

28 }

29 

30 int main() {

31     stack<int> S;

32     S.push(4);

33     S.push(3);

34     S.push(2);

35     S.push(1);

36     reversestack(S);

37     while (!S.empty()) {

38         cout << S.top() << endl;

39         S.pop();

40     }

41     return 0;

42 }

 

你可能感兴趣的:(struct)