-
Notifications
You must be signed in to change notification settings - Fork 267
/
DynamicQueue.cpp
93 lines (76 loc) · 1.49 KB
/
DynamicQueue.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
#include <cstddef>
#include <iostream>
struct Node {
int key;
Node *next;
Node(int key) : key(key), next(nullptr) {}
};
class DynamicQueue {
private:
Node *_begin;
Node *_end;
public:
DynamicQueue() : _begin(nullptr), _end(nullptr) {}
~DynamicQueue() {
while (_begin) {
Node *tmp = _begin;
_begin = _begin->next;
delete tmp;
}
}
bool isEmpty(void) const { return _begin == nullptr; }
void enqueue(int key) {
Node *node = new Node(key);
if (isEmpty()) {
_begin = node;
} else {
_end->next = node;
}
_end = node;
}
Node *dequeue(void) {
if (isEmpty()) {
return nullptr;
}
Node *removed = _begin;
_begin = _begin->next;
if (isEmpty()) {
_end = nullptr;
}
return removed;
}
size_t size(void) const {
size_t size = 0;
Node *curr = _begin;
while (curr) {
++size;
curr = curr->next;
}
return size;
}
void print(void) const {
if (isEmpty()) {
std::cout << "empty queue";
} else {
Node *curr = _begin;
while (curr) {
std::cout << curr->key << ' ';
curr = curr->next;
}
}
std::cout << std::endl;
}
};
int main(void) {
DynamicQueue queue;
queue.enqueue(42);
queue.enqueue(5);
queue.enqueue(1231);
queue.enqueue(515);
queue.print(); // 42 5 1231 515
// Use 'delete' keyword to make the code leak-free
queue.dequeue();
queue.dequeue();
queue.print(); // 1231 515
return 0;
}