TheAlgorithms/C++
1.0.0
All the algorithms implemented in C++
Toggle main menu visibility
Loading...
Searching...
No Matches
stack_using_queue.cpp
1
11
#include <cassert>
12
#include <cstdint>
13
#include <iostream>
14
#include <queue>
15
20
namespace
data_structures
{
27
namespace
stack_using_queue
{
31
struct
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
);
55
current_size
++;
56
}
57
62
void
pop
() {
63
if
(
main_q
.empty()) {
64
return
;
65
}
66
main_q
.pop();
67
current_size
--;
68
}
69
74
int
size
() {
return
current_size
; }
75
};
76
}
// namespace stack_using_queue
77
}
// namespace data_structures
78
83
static
void
test
() {
84
data_structures::stack_using_queue::Stack
s;
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
116
int
main
() {
117
test
();
// run self-test implementations
118
return
0;
119
}
test
void test()
Definition
caesar_cipher.cpp:100
main
int main()
Main function.
Definition
generate_parentheses.cpp:110
data_structures
for IO operations
stack_using_queue
Functions for the Stack Using Queue implementation.
data_structures::stack_using_queue::Stack
Stack Class implementation for basic methods of Stack Data Structure.
Definition
stack_using_queue.cpp:31
data_structures::stack_using_queue::Stack::auxiliary_q
std::queue< int64_t > auxiliary_q
Definition
stack_using_queue.cpp:33
data_structures::stack_using_queue::Stack::top
int top()
Definition
stack_using_queue.cpp:41
data_structures::stack_using_queue::Stack::pop
void pop()
Removes the topmost element from the stack.
Definition
stack_using_queue.cpp:62
data_structures::stack_using_queue::Stack::size
int size()
Utility function to return the current size of the stack.
Definition
stack_using_queue.cpp:74
data_structures::stack_using_queue::Stack::main_q
std::queue< int64_t > main_q
stores the current state of the stack
Definition
stack_using_queue.cpp:32
data_structures::stack_using_queue::Stack::push
void push(int val)
Inserts an element to the top of the stack.
Definition
stack_using_queue.cpp:48
data_structures::stack_using_queue::Stack::current_size
uint32_t current_size
stores the current size of the stack
Definition
stack_using_queue.cpp:35
data_structures
stack_using_queue.cpp
Generated by
1.18.0