Skip to content

Commit 36b8f83

Browse files
Merge pull request matthewsamuel95#283 from CircleJerkHug/master
Implementation of Stack using Queue
2 parents a6c7a8c + eed08f2 commit 36b8f83

File tree

3 files changed

+141
-0
lines changed

3 files changed

+141
-0
lines changed

.gitignore

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
.pyc
2+
a.out
3+
*.exe
Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
// CPP program to implement Queue using
2+
// one stack and recursive call stack.
3+
#include <bits/stdc++.h>
4+
using namespace std;
5+
6+
struct Queue {
7+
stack<int> s;
8+
9+
// Enqueue an item to the queue
10+
void enQueue(int x)
11+
{
12+
s.push(x);
13+
}
14+
15+
// Dequeue an item from the queue
16+
int deQueue()
17+
{
18+
if (s.empty()) {
19+
cout << "Q is empty";
20+
exit(0);
21+
}
22+
23+
// pop an item from the stack
24+
int x = s.top();
25+
s.pop();
26+
27+
// if stack becomes empty, return
28+
// the popped item
29+
if (s.empty())
30+
return x;
31+
32+
// recursive call
33+
int item = deQueue();
34+
35+
// push popped item back to the stack
36+
s.push(x);
37+
38+
// return the result of deQueue() call
39+
return item;
40+
}
41+
};
42+
43+
// Driver code
44+
int main()
45+
{
46+
Queue q;
47+
q.enQueue(1);
48+
q.enQueue(2);
49+
q.enQueue(3);
50+
51+
cout << q.deQueue() << '\n';
52+
cout << q.deQueue() << '\n';
53+
cout << q.deQueue() << '\n';
54+
55+
return 0;
56+
}
Lines changed: 82 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,82 @@
1+
// Program to implement a stack using two queue
2+
#include<bits/stdc++.h>
3+
using namespace std;
4+
5+
class Stack
6+
{
7+
// Two inbuilt queues
8+
queue<int> q1, q2;
9+
10+
// To maintain current number of
11+
// elements
12+
int curr_size;
13+
14+
public:
15+
Stack()
16+
{
17+
curr_size = 0;
18+
}
19+
20+
void push(int x)
21+
{
22+
curr_size++;
23+
24+
// Push x first in empty q2
25+
q2.push(x);
26+
27+
// Push all the remaining
28+
// elements in q1 to q2.
29+
while (!q1.empty())
30+
{
31+
q2.push(q1.front());
32+
q1.pop();
33+
}
34+
35+
// swap the names of two queues
36+
queue<int> q = q1;
37+
q1 = q2;
38+
q2 = q;
39+
}
40+
41+
void pop(){
42+
43+
// if no elements are there in q1
44+
if (q1.empty())
45+
return ;
46+
q1.pop();
47+
curr_size--;
48+
}
49+
50+
int top()
51+
{
52+
if (q1.empty())
53+
return -1;
54+
return q1.front();
55+
}
56+
57+
int size()
58+
{
59+
return curr_size;
60+
}
61+
};
62+
63+
// driver code
64+
int main()
65+
{
66+
Stack s;
67+
s.push(1);
68+
s.push(2);
69+
s.push(3);
70+
71+
cout << "current size: " << s.size()
72+
<< endl;
73+
cout << s.top() << endl;
74+
s.pop();
75+
cout << s.top() << endl;
76+
s.pop();
77+
cout << s.top() << endl;
78+
79+
cout << "current size: " << s.size()
80+
<< endl;
81+
return 0;
82+
}

0 commit comments

Comments
 (0)