Skip to content

Commit 612e8d5

Browse files
authored
Queue using two Stacks.cpp
1 parent eea74b3 commit 612e8d5

File tree

1 file changed

+86
-0
lines changed

1 file changed

+86
-0
lines changed

Queue using two Stacks.cpp

Lines changed: 86 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,86 @@
1+
#include<bits/stdc++.h>
2+
3+
using namespace std;
4+
5+
class StackQueue{
6+
private:
7+
stack<int> s1;
8+
stack<int> s2;
9+
public:
10+
void push(int B);
11+
int pop();
12+
13+
};
14+
int main()
15+
{
16+
17+
int T;
18+
cin>>T;
19+
while(T--)
20+
{
21+
StackQueue *sq = new StackQueue();
22+
23+
int Q;
24+
cin>>Q;
25+
while(Q--){
26+
int QueryType=0;
27+
cin>>QueryType;
28+
if(QueryType==1)
29+
{
30+
int a;
31+
cin>>a;
32+
sq->push(a);
33+
}else if(QueryType==2){
34+
cout<<sq->pop()<<" ";
35+
36+
}
37+
}
38+
cout<<endl;
39+
}
40+
41+
42+
}
43+
// } Driver Code Ends
44+
45+
46+
/* The structure of the class is
47+
class StackQueue{
48+
private:
49+
// These are STL stacks ( http://goo.gl/LxlRZQ )
50+
stack<int> s1;
51+
stack<int> s2;
52+
public:
53+
void push(int);
54+
int pop();
55+
}; */
56+
57+
/* The method push to push element into the queue */
58+
void StackQueue :: push(int x)
59+
{
60+
// Your Code
61+
while(!s1.empty())
62+
{
63+
s2.push(s1.top());
64+
s1.pop();
65+
}
66+
s1.push(x);
67+
while(!s2.empty())
68+
{
69+
s1.push(s2.top());
70+
s2.pop();
71+
}
72+
73+
}
74+
75+
/*The method pop which return the element poped out of the queue*/
76+
int StackQueue :: pop()
77+
{
78+
// Your Code
79+
int val=-1;
80+
if(!s1.empty())
81+
{
82+
val=s1.top();
83+
s1.pop();
84+
}
85+
return val;
86+
}

0 commit comments

Comments
 (0)