TheAlgorithms/C++ 1.0.0
All the algorithms implemented in C++
Loading...
Searching...
No Matches
stack_using_queue.cpp
1
11#include <cassert>
12#include <cstdint>
13#include <iostream>
14#include <queue>
15
20namespace data_structures {
27namespace stack_using_queue {
31struct Stack {
32 std::queue<int64_t> main_q;
33 std::queue<int64_t> auxiliary_q;
35 uint32_t current_size = 0;
36
41 int top() { return main_q.front(); }
42
48 void push(int val) {
49 auxiliary_q.push(val);
50 while (!main_q.empty()) {
51 auxiliary_q.push(main_q.front());
52 main_q.pop();
53 }
54 swap(main_q, auxiliary_q);
56 }
57
62 void pop() {
63 if (main_q.empty()) {
64 return;
65 }
66 main_q.pop();
68 }
69
74 int size() { return current_size; }
75};
76} // namespace stack_using_queue
77} // namespace data_structures
78
83static void test() {
85 s.push(1);
86 s.push(2);
87 s.push(3);
88
89 assert(s.size() == 3);
90
91 assert(s.top() == 3);
92
93 s.pop();
94 assert(s.top() == 2);
95
96 s.pop();
97 assert(s.top() == 1);
98
99 s.push(5);
100 assert(s.top() == 5);
101
102 s.pop();
103 assert(s.top() == 1);
104
105 assert(s.size() == 1);
106}
107
116int main() {
117 test(); // run self-test implementations
118 return 0;
119}
void test()
int main()
Main function.
for IO operations
Functions for the Stack Using Queue implementation.
Stack Class implementation for basic methods of Stack Data Structure.
void pop()
Removes the topmost element from the stack.
int size()
Utility function to return the current size of the stack.
std::queue< int64_t > main_q
stores the current state of the stack
void push(int val)
Inserts an element to the top of the stack.
uint32_t current_size
stores the current size of the stack