-
Notifications
You must be signed in to change notification settings - Fork 361
/
Copy pathreverseasttring.cpp
81 lines (73 loc) · 1.45 KB
/
reverseasttring.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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
stack<int> st;
//pushin function to insert elements at correct position
void pushin(int t){
if(st.size()==0){
st.push(t);
return;
}
else{
int val=st.top();
st.pop();
pushin(t);
st.push(val);
return;
}
}
//reverse function
void reverse(){
if(st.size()==1)return;
int temp=st.top();
st.pop();
reverse();
pushin(temp);
return;
}
// Driver Code
int main()
{
// push elements into
// the stack
st.push(1);
st.push(2);
st.push(3);
st.push(4);
cout<<"Original Stack"<<endl;
// print the elements
// of original stack
vector<int>v;
while(!st.empty())
{
int p=st.top();
st.pop();
v.push_back(p);
}
//display of reversed stack
for(int i=0;i<v.size();i++){
cout<<v[i]<<" ";
}
st.push(1);
st.push(2);
st.push(3);
st.push(4);
// function to reverse
// the stack
reverse();
cout<<"\nReversed Stack"
<<endl;
// storing values of reversed
v.clear();
while(!st.empty())
{
int p=st.top();
st.pop();
v.push_back(p);
}
//display of reversed stack
for(int i=0;i<v.size();i++){
cout<<v[i]<<" ";
}
return 0;
}