-
-
Notifications
You must be signed in to change notification settings - Fork 7.3k
/
queue_using_two_stacks.cpp
144 lines (128 loc) · 2.64 KB
/
queue_using_two_stacks.cpp
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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
/**
* @author [shoniavika](https://github.com/shoniavika)
* @file
*
* Implementation of a Queue using two Stacks.
*/
#include <cassert>
#include <iostream>
#include <stack>
namespace {
/**
* @brief Queue data structure. Stores elements in FIFO
* (first-in-first-out) manner.
* @tparam T datatype to store in the queue
*/
template <typename T>
class MyQueue {
private:
std::stack<T> s1, s2;
public:
/**
* Constructor for queue.
*/
MyQueue() = default;
/**
* Pushes x to the back of queue.
*/
void push(T x);
/**
* Removes an element from the front of the queue.
*/
const T& pop();
/**
* Returns first element, without removing it.
*/
const T& peek() const;
/**
* Returns whether the queue is empty.
*/
bool empty() const;
};
/**
* Appends element to the end of the queue
*/
template <typename T>
void MyQueue<T>::push(T x) {
while (!s2.empty()) {
s1.push(s2.top());
s2.pop();
}
s2.push(x);
while (!s1.empty()) {
s2.push(s1.top());
s1.pop();
}
}
/**
* Removes element from the front of the queue
*/
template <typename T>
const T& MyQueue<T>::pop() {
const T& temp = MyQueue::peek();
s2.pop();
return temp;
}
/**
* Returns element in the front.
* Does not remove it.
*/
template <typename T>
const T& MyQueue<T>::peek() const {
if (!empty()) {
return s2.top();
}
std::cerr << "Queue is empty" << std::endl;
exit(0);
}
/**
* Checks whether a queue is empty
*/
template <typename T>
bool MyQueue<T>::empty() const {
return s2.empty() && s1.empty();
}
} // namespace
/**
* Testing function
*/
void queue_test() {
MyQueue<int> que;
std::cout << "Test #1\n";
que.push(2);
que.push(5);
que.push(0);
assert(que.peek() == 2);
assert(que.pop() == 2);
assert(que.peek() == 5);
assert(que.pop() == 5);
assert(que.peek() == 0);
assert(que.pop() == 0);
assert(que.empty() == true);
std::cout << "PASSED\n";
std::cout << "Test #2\n";
que.push(-1);
assert(que.empty() == false);
assert(que.peek() == -1);
assert(que.pop() == -1);
std::cout << "PASSED\n";
MyQueue<double> que2;
std::cout << "Test #3\n";
que2.push(2.31223);
que2.push(3.1415926);
que2.push(2.92);
assert(que2.peek() == 2.31223);
assert(que2.pop() == 2.31223);
assert(que2.peek() == 3.1415926);
assert(que2.pop() == 3.1415926);
assert(que2.peek() == 2.92);
assert(que2.pop() == 2.92);
std::cout << "PASSED\n";
}
/**
* Main function, calls testing function
*/
int main() {
queue_test();
return 0;
}