-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathReverseStack.cpp
More file actions
60 lines (52 loc) · 1.02 KB
/
ReverseStack.cpp
File metadata and controls
60 lines (52 loc) · 1.02 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
#include <iostream>
#include <stack>
using namespace std;
//reverse a stack using 1 extra stack
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(2);
s.push(3);
s.push(4);
reverseStackRec(s);
while(s.empty() == false){
cout << s.top() << " ";
s.pop();
}
return 0;
}