-
Notifications
You must be signed in to change notification settings - Fork 213
Expand file tree
/
Copy pathQueue_using_single_Stack.cpp
More file actions
91 lines (89 loc) · 1.86 KB
/
Queue_using_single_Stack.cpp
File metadata and controls
91 lines (89 loc) · 1.86 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
/* @author [saqlain] (https://github.com/Mysterious786)
* @file
*
* Implementation of a Queue using Single Stacks.
*/
#include <iostream>
#include <stack>
#include <cstdlib>
#include<queue>
using namespace std;
/**
* Queue data structure.Store elements in FIFO
* (first-in-first-out) manner.
*
*/
class Queue
{
std::stack<int> s;
public:
/**
* Pushes data to the back of queue
*/
void enqueue(int data){
/**
* Push item into the First Stack
*/
s.push(data);
}
/**
* Remove an item from the queue
*/
int dequeue()
{
/**
* Determines whether the stack is empty
*/
if (s.empty())
{
cout << "Underflow!!";
exit(0);
}
/**
*Removes item from the Stack
*/
int top = s.top();
s.pop();
/**
* Determines whether the stack becomes empty,and returns the popped item
*/
if (s.empty())
{
return top;
}
/**
* Recursion call
*/
int item = dequeue();
/**
* push popped item back into the stack
*/
s.push(top);
/**
* return the result of dequeue() call
*/
return item;
}
};
/**
* Main function, calls enqueue and dequeue
*/
int main()
{
int keys[] = {1, 2, 3, 4, 5};
Queue q;
/**
* Adding key to the Queue
*/
for (int key : keys)
{
q.enqueue(key);
}
/**
* Print
*
*/
cout << q.dequeue() << " ";
cout << q.dequeue() << " ";
return 0;
}