Skip to content

Commit c991b72

Browse files
committed
Implementing Queue Using Two Stacks
1 parent 738cf2a commit c991b72

File tree

1 file changed

+15
-19
lines changed

1 file changed

+15
-19
lines changed

Queue/queue_using_stack.cpp

Lines changed: 15 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -6,37 +6,33 @@ struct Queue {
66
// Add an item to the queue
77
void enQueue(int x)
88
{
9-
// Move all elements from first stack (s1) to second stack (s2)
10-
while (!s1.empty()) {
11-
s2.push(s1.top());
12-
s1.pop();
13-
}
14-
// Push item into first stack (s1)
9+
// Push item into the first stack (s1)
1510
s1.push(x);
16-
// Push everything back to first stack (s1)
17-
while (!s2.empty()) {
18-
s1.push(s2.top());
19-
s2.pop();
20-
}
2111
}
22-
2312
// Remove an item from the queue
2413
int deQueue()
2514
{
26-
// If first stack (s1) is empty, then exit
27-
if (s1.empty()) {
15+
// If both stacks are empty, then exit
16+
if (s1.empty() && s2.empty()){
2817
cout << "Queue is Empty, thus deletion cannot be performed\n";
2918
return -1;
3019
}
3120

32-
// Else return top of first stack (s1)
33-
int x = s1.top();
34-
s1.pop();
21+
// If second stack (s2) is empty, move elements from first stack (s1) to second stack (s2)
22+
if (s2.empty()) {
23+
while (!s1.empty()){
24+
s2.push(s1.top());
25+
s1.pop();
26+
}
27+
}
28+
// Return the top item from second stack (s2)
29+
int x = s2.top();
30+
s2.pop();
3531
return x;
3632
}
3733
void sizeQueue()
3834
{
39-
cout<<"Size of the Queue: "<<s1.size()<<endl;
35+
cout<<"Size of the Queue: "<<s1.size()+s2.size()<<endl;
4036
}
4137
};
4238

@@ -45,7 +41,7 @@ int main()
4541
Queue q;
4642
int x, data;
4743
do
48-
{
44+
{
4945
cout<<"\nMain Menu: \n";
5046
cout<<"1. Insertion to Queue \n";
5147
cout<<"2. Deletion from Queue \n";

0 commit comments

Comments
 (0)