Skip to content

Commit cee8c04

Browse files
committed
Implementing Queue Using Single Stack
1 parent faefb14 commit cee8c04

File tree

2 files changed

+79
-1
lines changed

2 files changed

+79
-1
lines changed

Queue/queue_using_single_stack.cpp

Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
#include <bits/stdc++.h>
2+
using namespace std;
3+
4+
struct Queue {
5+
stack<int> s;
6+
// Add an item to the queue
7+
void enQueue(int x)
8+
{
9+
s.push(x);
10+
}
11+
// Remove an item from the queue
12+
int deQueue()
13+
{
14+
15+
if (s.empty()) {
16+
cout << "Queue is Empty, thus deletion cannot be performed\n";
17+
return -1;
18+
}
19+
20+
// Pop an item from the stack
21+
int x = s.top();
22+
s.pop();
23+
24+
// If the stack becomes empty, then return the popped item
25+
if (s.empty())
26+
return x;
27+
28+
// Recursive call of Dequeue Function
29+
int item = deQueue();
30+
31+
// Push popped item back to the stack
32+
s.push(x);
33+
34+
// Return the result of deQueue() function call
35+
return item;
36+
}
37+
void sizeQueue()
38+
{
39+
cout<<"Size of the Queue: "<<s.size()<<endl;
40+
}
41+
};
42+
43+
int main()
44+
{
45+
Queue q;
46+
int x, data;
47+
do
48+
{
49+
cout<<"\nMain Menu: \n";
50+
cout<<"1. Insertion to Queue \n";
51+
cout<<"2. Deletion from Queue \n";
52+
cout<<"3. Size of Queue\n";
53+
cout<<"4. Quit\n";
54+
cout<<"Enter your choice (1-4): ";
55+
cin>>x;
56+
switch(x)
57+
{
58+
case 1: cout<<"Enter the value to be inserted in Queue: ";
59+
cin>>data;
60+
q.enQueue(data);
61+
break;
62+
case 2: data = q.deQueue();
63+
if(data!=-1)
64+
cout<<"The deleted element is: "<<data<<endl;
65+
break;
66+
case 3: q.sizeQueue();
67+
break;
68+
case 4: exit(0);
69+
default: cout<<"Invalid Choice Entered\n";
70+
}
71+
}
72+
while(true);
73+
return 0;
74+
}

README.md

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,11 @@ This is a repository containing various C++ Programs to understand the basic con
66

77
* [Queue Using Stack](https://github.com/altruistcoder/Data-Structures/blob/master/Queue/queue_using_stack.cpp):
88

9-
C++ Code for implementing a queue using stacks.
9+
C++ Code for implementing a queue using two stacks.
10+
11+
* [Queue Using Stack](https://github.com/altruistcoder/Data-Structures/blob/master/Queue/queue_using_single_stack.cpp):
12+
13+
C++ Code for implementing a queue using single stack (using recursion).
1014

1115
* [Merge Sort](https://github.com/altruistcoder/Data-Structures/blob/master/Sorting%20Programs/merge_sort.cpp):
1216

0 commit comments

Comments
 (0)