-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathStack_reverse.cpp
64 lines (56 loc) · 993 Bytes
/
Stack_reverse.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
#include<iostream>
#include<stack>
using namespace std;
void transfer(stack<int>& s1,stack<int>& s2,int n){
for(int i=0;i<n;i++){
s2.push(s1.top());
s1.pop();
}
}
void reverseStack(stack<int>& s1){
stack<int> s2;
int n = s1.size();
for(int i=0;i<n;i++){
int x = s1.top();
s1.pop();
transfer(s1,s2,n-i-1);
s1.push(x);
transfer(s2,s1,n-i-1);
}
}
void insertAtBottom(stack<int>& s,int x){
if(s.empty()){
s.push(x);
return;
}
int y = s.top();
s.pop();
insertAtBottom(s,x);
s.push(y);
}
void reverseStackRec(stack<int>& s){
if(s.empty()) return;
int x = s.top();
s.pop();
reverseStackRec(s);
insertAtBottom(s,x);
}
int main(){
stack<int> s;
s.push(1);
s.push(11);
s.push(91);
s.push(31);
s.push(19);
// while(s.empty()==false){
// cout<<s.top()<<" ";
// s.pop();
// }
// cout<<endl;
reverseStackRec(s);
while(s.empty()==false){
cout<<s.top()<<" ";
s.pop();
}
return 0;
}