-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMedium_Prob53.cpp
More file actions
57 lines (47 loc) · 1.27 KB
/
Medium_Prob53.cpp
File metadata and controls
57 lines (47 loc) · 1.27 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
/* Implement a queue using two stacks. Recall that a queue is a FIFO (first-in, first-out) data structure with the following methods: enqueue, which inserts an element into the queue, and dequeue, which removes it. */
#include <iostream>
#include <stack>
using namespace std;
template <typename T>
class Queue{
private :
stack<T> stack1;
stack<T> stack2;
public:
void enqueue(const T& newItem){
if (!(stack1.empty())){
while (!stack1.empty())
{
stack2.push(stack1.top());
stack1.pop();
}
stack1.push(newItem);
while (!stack2.empty()){
stack1.push(stack2.top());
stack2.pop();
}
} else {
stack1.push(newItem);
}
}
void dequeue(){
stack1.pop();
}
T top(){
return stack1.top();
}
bool empty(){
return stack1.empty();
}
};
int main(int argc, char *argv[])
{
Queue<int> queue ;
for (int i=0; i<5; i++){
queue.enqueue(i);
}
while (!queue.empty()){
cout << queue.top() << endl;
queue.dequeue();
}
}