-
Notifications
You must be signed in to change notification settings - Fork 46
Expand file tree
/
Copy pathReverseStackRecursion.cpp
More file actions
68 lines (58 loc) · 1.09 KB
/
ReverseStackRecursion.cpp
File metadata and controls
68 lines (58 loc) · 1.09 KB
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
// Problem: Reverse Stack using Recursion
// Time complexity: O(n^2)
// Space Complexity: O(n)
#include <bits/stdc++.h>
using namespace std;
void pushAtBottom(stack<int> &st, int x)
{
if (st.size() == 0)
{
st.push(x);
}
else
{
int a = st.top();
st.pop();
pushAtBottom(st, x);
st.push(a);
}
}
void reverse(stack<int> &st)
{
if (st.size() > 0)
{
int x = st.top();
st.pop();
reverse(st);
pushAtBottom(st, x);
}
return;
}
int main()
{
stack<int> st, st2;
// intializing the stack with some elements
for (int i = 1; i <= 4; i++)
{
st.push(i);
}
st2 = st;
// printing the original stack
cout << "Original Stack" << endl;
while (!st2.empty())
{
cout << st2.top() << " ";
st2.pop();
}
cout << endl;
// function call to reverse the stack
reverse(st);
// printing the reversed stack
cout << "Reversed Stack" << endl;
while (!st.empty())
{
cout << st.top() << " ";
st.pop();
}
return 0;
}