-
Notifications
You must be signed in to change notification settings - Fork 1
/
linkedQueue.cpp
113 lines (101 loc) · 1.92 KB
/
linkedQueue.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
// create on 2016-01-15
#include <iostream>
enum ErrorCode {
success,
underflow,
overflow
};
template <class QueueEntry>
struct Node {
QueueEntry data;
Node<QueueEntry> *next;
Node(QueueEntry val): data(val), next(NULL) {}
};
template <typename QueueEntry>
class MyQueue {
public:
MyQueue();
bool empty() const;
ErrorCode append(const QueueEntry& item);
ErrorCode serve();
ErrorCode retrieve(QueueEntry& item) const;
int size() const;
void clear();
ErrorCode retrieve_and_serve(QueueEntry& item);
private:
Node<QueueEntry>* front;
Node<QueueEntry>* rear;
};
template <typename T>
MyQueue<T>::MyQueue() {
front = rear = NULL;
}
template <typename T>
bool MyQueue<T>::empty() const {
return front == NULL;
}
template <typename T>
ErrorCode MyQueue<T>::append(const T& item) {
Node<T> *newNode = new Node<T>(item);
if (empty()) {
front = rear = newNode;
} else {
rear->next = newNode;
rear = newNode;
}
return success;
}
template <typename T>
ErrorCode MyQueue<T>::serve() {
Node<T>* toDelete = NULL;
ErrorCode ans = success;
if (empty()) {
ans = underflow;
} else if (size() == 1) {
toDelete = front;
front = rear = NULL;
delete toDelete;
} else {
toDelete = front;
front = front->next;
delete toDelete;
}
return ans;
}
template <typename T>
ErrorCode MyQueue<T>::retrieve(T& item) const {
ErrorCode ans = success;
if (empty()) {
ans = underflow;
} else {
item = front->data;
}
return ans;
}
template <typename T>
int MyQueue<T>::size() const {
Node<T>* ptr = front;
int count = 0;
while (ptr) {
ptr = ptr->next;
++count;
}
return count;
}
template <typename T>
void MyQueue<T>::clear() {
Node<T>* toDelete = NULL;
while (front) {
toDelete = front;
front = front->next;
delete toDelete;
}
front = rear = NULL;
}
template <typename T>
ErrorCode MyQueue<T>::retrieve_and_serve(T& item) {
ErrorCode ans = success;
ans = retrieve(item);
serve();
return ans;
}