-
Notifications
You must be signed in to change notification settings - Fork 40
/
reversestack.cpp
62 lines (49 loc) · 967 Bytes
/
reversestack.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
#include<iostream>
#include<stack>
using namespace std;
void insertAtBottom(stack<int>&s,int target){
//base case
if(s.empty()){
s.push(target);
return ;
}
int topEle=s.top();
s.pop();
//recursive call
insertAtBottom(s,target);
//bactracking
s.push(topEle);
}
void reverseStack(stack<int>&s){
//base case
if(s.empty()){
return ;
}
//ab nhi pata
int target=s.top();
s.pop();
//reverse stack
reverseStack(s);
//insert at bottom target ko
insertAtBottom(s,target);
}
int main(){
stack<int>s;
s.push(10);
s.push(1);
s.push(4);
s.push(9);
s.push(2);
// cout<<"Print stack"<<endl;
// while(!s.empty()){
// cout<<s.top()<<" ";
// s.pop();
// }
reverseStack(s);
cout<<"Print stack after reverse"<<endl;
while(!s.empty()){
cout<<s.top()<<" ";
s.pop();
}
cout<<endl;
}