Skip to content

Commit 0cc47d1

Browse files
committed
Implementing Stack Using Two Queues
1 parent afd251f commit 0cc47d1

File tree

1 file changed

+110
-0
lines changed

1 file changed

+110
-0
lines changed

Stack/stack_using_two_queues.cpp

Lines changed: 110 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,110 @@
1+
#include <bits/stdc++.h>
2+
using namespace std;
3+
4+
class Stack
5+
{
6+
// Initailize objects of two in-built queues.
7+
queue<int> q1, q2;
8+
// To maintain current size of stack
9+
int curr_size;
10+
11+
public:
12+
Stack()
13+
{
14+
curr_size = 0;
15+
}
16+
17+
void push(int x)
18+
{
19+
q1.push(x);
20+
curr_size++;
21+
}
22+
23+
void pop(){
24+
if (q1.empty())
25+
{
26+
cout << "Stack is Empty, thus deletion cannot be performed\n";
27+
return;
28+
}
29+
// Leave one element in q1 and push all other elements in second queue (q2).
30+
while (q1.size() != 1)
31+
{
32+
q2.push(q1.front());
33+
q1.pop();
34+
}
35+
// Pop the only left element from first queue (q1)
36+
cout<<"The popped element is: "<<q1.front()<<endl;
37+
q1.pop();
38+
curr_size--;
39+
// Swap the names of two queues
40+
queue<int> q = q1;
41+
q1 = q2;
42+
q2 = q;
43+
return;
44+
}
45+
46+
void top()
47+
{
48+
if (q1.empty())
49+
{
50+
cout<<"Stack is Empty\n";
51+
return;
52+
}
53+
while( q1.size() != 1 )
54+
{
55+
q2.push(q1.front());
56+
q1.pop();
57+
}
58+
// Last pushed element to Stack
59+
int temp = q1.front();
60+
cout<<"The Top Element of Stack is: "<<temp<<endl;
61+
// To empty the auxiliary queue after last operation
62+
q1.pop();
63+
// Push last element to second queue (q2)
64+
q2.push(temp);
65+
// Swap the names of the two queues
66+
queue<int> q = q1;
67+
q1 = q2;
68+
q2 = q;
69+
return;
70+
}
71+
72+
int sizeStack()
73+
{
74+
cout<<"Size of the Stack: "<<curr_size<<endl;
75+
}
76+
};
77+
78+
int main()
79+
{
80+
Stack s;
81+
int x, data;
82+
do
83+
{
84+
cout<<"Main Menu \n";
85+
cout<<"1. Insertion to Stack (Push Operation) \n";
86+
cout<<"2. Deletion from Stack (Pop Operation) \n";
87+
cout<<"3. Return Top Element from Stack \n";
88+
cout<<"4. Size of Stack\n";
89+
cout<<"5. Quit \n";
90+
cout<<"Enter your choice (1-5): ";
91+
cin>>x;
92+
switch(x)
93+
{
94+
case 1: cout<<"Enter the value to be inserted in Stack: ";
95+
cin>>data;
96+
s.push(data);
97+
break;
98+
case 2: s.pop();
99+
break;
100+
case 3: s.top();
101+
break;
102+
case 4: s.sizeStack();
103+
break;
104+
case 5: exit(0);
105+
default: cout<<"Invalid Choice Entered\n";
106+
}
107+
}
108+
while(true);
109+
return 0;
110+
}

0 commit comments

Comments
 (0)