Skip to content

Commit 089c3ed

Browse files
Merge pull request matthewsamuel95#287 from dreamerHarshit/new_master
Program to implement queue using stack.
2 parents 0c41186 + e349cb7 commit 089c3ed

File tree

2 files changed

+80
-0
lines changed

2 files changed

+80
-0
lines changed

DataStructures/Queue/queue_using_stack.cpp

Whitespace-only changes.
Lines changed: 80 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,80 @@
1+
/* Program to implement a stack using
2+
two queue */
3+
#include<bits/stdc++.h>
4+
using namespace std;
5+
6+
class Stack
7+
{
8+
queue<int> q1, q2;
9+
10+
int curr_size;
11+
12+
public:
13+
Stack()
14+
{
15+
curr_size = 0;
16+
}
17+
18+
void push(int x)
19+
{
20+
curr_size++;
21+
22+
// Push x first in empty q2
23+
q2.push(x);
24+
25+
// Push all the remaining
26+
// elements in q1 to q2.
27+
while (!q1.empty())
28+
{
29+
q2.push(q1.front());
30+
q1.pop();
31+
}
32+
33+
// swap the names of two queues
34+
queue<int> q = q1;
35+
q1 = q2;
36+
q2 = q;
37+
}
38+
39+
void pop(){
40+
41+
// if no elements are there in q1
42+
if (q1.empty())
43+
return ;
44+
q1.pop();
45+
curr_size--;
46+
}
47+
48+
int top()
49+
{
50+
if (q1.empty())
51+
return -1;
52+
return q1.front();
53+
}
54+
55+
int size()
56+
{
57+
return curr_size;
58+
}
59+
};
60+
61+
//main function
62+
int main()
63+
{
64+
Stack stk;
65+
stk.push(1);
66+
stk.push(2);
67+
stk.push(3);
68+
69+
cout << "current size: " << stk.size()
70+
<< endl;
71+
cout << stk.top() << endl;
72+
stk.pop();
73+
cout << stk.top() << endl;
74+
stk.pop();
75+
cout << stk.top() << endl;
76+
77+
cout << "current size: " << stk.size()
78+
<< endl;
79+
return 0;
80+
}

0 commit comments

Comments
 (0)