-
Notifications
You must be signed in to change notification settings - Fork 137
Expand file tree
/
Copy pathreverse_stack.cpp
More file actions
77 lines (63 loc) · 1.08 KB
/
reverse_stack.cpp
File metadata and controls
77 lines (63 loc) · 1.08 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
// contributed by:prashant kumar
// C++ code to reverse a
// stack using recursion
#include<bits/stdc++.h>
using namespace std;
//for stack implementation
stack<char> st;
// initializing a string to store
string s;
// insert a element at the bottom of a stack.
char insert_at_bottom(char x)
{
if(st.size() == 0)
st.push(x);
else
{
char a = st.top();
st.pop();
insert_at_bottom(x);
st.push(a);
}
}
// reverse function nusing insert_at_bottom
char reverse()
{
if(st.size()>0)
{
char x = st.top();
st.pop();
reverse();
insert_at_bottom(x);
}
}
// Driver Code
int main()
{
// push elements in the stack
st.push('1');
st.push('2');
st.push('3');
st.push('4');
cout<<"Original Stack"<<endl;
// print the elements (old stack)
cout<<"1"<<" "<<"2"<<" "
<<"3"<<" "<<"4"
<<endl;
// reverse Function and the stack
reverse();
cout<<"Reversed Stack"
<<endl;
while(!st.empty())
{
char p=st.top();
st.pop();
s+=p;
}
//for reversed stack
cout<<s[3]<<" "<<s[2]<<" "
<<s[1]<<" "<<s[0]<<endl;
return 0;
}
// time complexity of O(n^2)
// thank you