-
Notifications
You must be signed in to change notification settings - Fork 15
/
Reverse_stack_using_recursion.cpp
92 lines (79 loc) · 1.93 KB
/
Reverse_stack_using_recursion.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
// C++ code to reverse a
// stack using recursion
#include <bits/stdc++.h>
using namespace std;
// Below is a recursive function
// that inserts an element
// at the bottom of a stack.
void insert_at_bottom(stack<int>& st, int x)
{
if (st.size() == 0) {
st.push(x);
}
else {
// All items are held in Function Call
// Stack until we reach end of the stack
// When the stack becomes empty, the
// st.size() becomes 0, the above if
// part is executed and the item is
// inserted at the bottom
int a = st.top();
st.pop();
insert_at_bottom(st, x);
// push allthe items held in
// Function Call Stack
// once the item is inserted
// at the bottom
st.push(a);
}
}
// Below is the function that
// reverses the given stack using
// insert_at_bottom()
void reverse(stack<int>& st)
{
if (st.size() > 0) {
// Hold all items in Function
// Call Stack until we
// reach end of the stack
int x = st.top();
st.pop();
reverse(st);
// Insert all the items held
// in Function Call Stack
// one by one from the bottom
// to top. Every item is
// inserted at the bottom
insert_at_bottom(st, x);
}
return;
}
// Driver Code
int main()
{
stack<int> st, st2;
// push elements into
// the stack
for (int i = 1; i <= 4; i++) {
st.push(i);
}
st2 = st;
cout << "Original Stack" << endl;
// printing the stack after reversal
while (!st2.empty()) {
cout << st2.top() << " ";
st2.pop();
}
cout<<endl;
// function to reverse
// the stack
reverse(st);
cout << "Reversed Stack" << endl;
// printing the stack after reversal
while (!st.empty()) {
cout << st.top() << " ";
st.pop();
}
return 0;
}
// by HIMANSHU AGGARWAL