forked from imsushant12/GFG-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Reverse_a_stack-using_recursion.cpp
67 lines (56 loc) · 1.02 KB
/
Reverse_a_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
/*
Problem Statement:
------------------
Write a program to reverse a stack using recursion. You are not allowed to use loop constructs like while, for..etc, and you can only use the following ADT functions on Stack S:
isEmpty(S)
push(S)
pop(S)
*/
// Link -->
// Code:
#include <bits/stdc++.h>
using namespace std;
void insertAtBottom(stack<int> &s, int element)
{
if (s.empty())
{
s.push(element);
return;
}
int top = s.top();
s.pop();
insertAtBottom(s, element);
s.push(top);
}
void reverse(stack<int> &s)
{
if (s.empty())
return;
int current = s.top();
s.pop();
reverse(s);
insertAtBottom(s, current);
}
void printStack(stack<int> s)
{
stack<int> temp;
temp = s;
while (!temp.empty())
{
cout << s.top() << " ";
s.pop();
}
}
int main()
{
stack<int> s;
s.push(1);
s.push(2);
s.push(3);
s.push(4);
s.push(5);
reverse(s);
cout << "\nReversed Stack is : ";
printStack(s);
return 0;
}