forked from aditya2499/Data-Structures-and-algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStackReversal
More file actions
109 lines (90 loc) · 1.92 KB
/
StackReversal
File metadata and controls
109 lines (90 loc) · 1.92 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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
// C++ code to reverse a
// stack using recursion
#include<bits/stdc++.h>
using namespace std;
// using std::stack for
// stack implementation
stack<char> st;
// intializing a string to store
// result of reversed stack
string ns;
// Below is a recursive function
// that inserts an element
// at the bottom of a stack.
char insert_at_bottom(char 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
char a = st.top();
st.pop();
insert_at_bottom(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()
char reverse()
{
if(st.size()>0)
{
// Hold all items in Function
// Call Stack until we
// reach end of the stack
char x = st.top();
st.pop();
reverse();
// 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(x);
}
}
// Driver Code
int main()
{
// push elements into
// the stack
st.push('1');
st.push('2');
st.push('3');
st.push('4');
cout<<"Original Stack"<<endl;
// print the elements
// of original stack
cout<<"1"<<" "<<"2"<<" "
<<"3"<<" "<<"4"
<<endl;
// function to reverse
// the stack
reverse();
cout<<"Reversed Stack"
<<endl;
// storing values of reversed
// stack into a string for display
while(!st.empty())
{
char p=st.top();
st.pop();
ns+=p;
}
//display of reversed stack
cout<<ns[3]<<" "<<ns[2]<<" "
<<ns[1]<<" "<<ns[0]<<endl;
return 0;
}
// This code is contributed by Gautam Singh