-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathreverse_stack_using_recursion.cpp
More file actions
63 lines (53 loc) · 1002 Bytes
/
reverse_stack_using_recursion.cpp
File metadata and controls
63 lines (53 loc) · 1002 Bytes
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
#include<iostream>
#include<algorithm>
#include<stack>
#include<vector>
using namespace std;
void putAtDepth(stack<int>* s, int e, int depth) {
if(depth == 1) {
int holder = s->top();
s->pop();
s->push(e);
s->push(holder);
}
else {
int holder = s->top();
s->pop();
putAtDepth(s,e,depth-1);
s->push(holder);
}
}
void reverse(stack<int>*s) {
for(int i=0;i<s->size()-1;i++){
int holder = s->top();
s->pop();
putAtDepth(s,holder,s->size()-i);
}
}
void printStack(stack<int>* s){
stack<int> temp;
while(!s->empty()) {
cout<<s->top()<<" ";
temp.push(s->top());
s->pop();
}
while(!temp.empty()) {
s->push(temp.top());
temp.pop();
}
cout<<endl;
}
int main() {
stack<int> s;
int elems, val;
cin>>elems;
while(elems--) {
cin>>val;
s.push(val);
}
cout<<"==== before ==="<<endl;
printStack(&s);
reverse(&s);
cout<<"==== after ==="<<endl;
printStack(&s);
}