TheAlgorithms/C++ 1.0.0
All the algorithms implemented in C++
Loading...
Searching...
No Matches
queue_using_two_stacks.cpp
Go to the documentation of this file.
1
8#include <cassert>
9#include <iostream>
10#include <stack>
11
12namespace {
18template <typename T>
19class MyQueue {
20 private:
21 std::stack<T> s1, s2;
22
23 public:
27 MyQueue() = default;
28
32 void push(T x);
33
37 const T& pop();
38
42 const T& peek() const;
43
47 bool empty() const;
48};
49
53template <typename T>
54void MyQueue<T>::push(T x) {
55 while (!s2.empty()) {
56 s1.push(s2.top());
57 s2.pop();
58 }
59 s2.push(x);
60 while (!s1.empty()) {
61 s2.push(s1.top());
62 s1.pop();
63 }
64}
65
69template <typename T>
70const T& MyQueue<T>::pop() {
71 const T& temp = MyQueue::peek();
72 s2.pop();
73 return temp;
74}
75
80template <typename T>
81const T& MyQueue<T>::peek() const {
82 if (!empty()) {
83 return s2.top();
84 }
85 std::cerr << "Queue is empty" << std::endl;
86 exit(0);
87}
88
92template <typename T>
93bool MyQueue<T>::empty() const {
94 return s2.empty() && s1.empty();
95}
96} // namespace
97
102 MyQueue<int> que;
103 std::cout << "Test #1\n";
104 que.push(2);
105 que.push(5);
106 que.push(0);
107 assert(que.peek() == 2);
108 assert(que.pop() == 2);
109 assert(que.peek() == 5);
110 assert(que.pop() == 5);
111 assert(que.peek() == 0);
112 assert(que.pop() == 0);
113 assert(que.empty() == true);
114 std::cout << "PASSED\n";
115
116 std::cout << "Test #2\n";
117 que.push(-1);
118 assert(que.empty() == false);
119 assert(que.peek() == -1);
120 assert(que.pop() == -1);
121 std::cout << "PASSED\n";
122
123 MyQueue<double> que2;
124 std::cout << "Test #3\n";
125 que2.push(2.31223);
126 que2.push(3.1415926);
127 que2.push(2.92);
128
129 assert(que2.peek() == 2.31223);
130 assert(que2.pop() == 2.31223);
131 assert(que2.peek() == 3.1415926);
132 assert(que2.pop() == 3.1415926);
133 assert(que2.peek() == 2.92);
134 assert(que2.pop() == 2.92);
135 std::cout << "PASSED\n";
136}
137
141int main() {
142 queue_test();
143 return 0;
144}
void queue_test()