-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathpQueue.h
128 lines (103 loc) · 1.88 KB
/
pQueue.h
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
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
#ifndef __PQUEUE_H__
#define __PQUEUE_H__
#define NULL 0
template <class T>
class pQueue {
private:
struct q_item {
q_item* next = nullptr;
q_item* prev = nullptr;
unsigned int priority;
T data;
q_item (const T& data, const unsigned int& priority) : data(data), priority(priority)
{}
};
q_item* start;
q_item* end;
unsigned int size;
public:
pQueue() : start(nullptr), end(nullptr), size(0)
{}
~pQueue() {
q_item* tmp = nullptr;
while (end != nullptr) {
tmp = end;
end = end->prev;
delete[] tmp;
}
}
void push_back(const T& item, const unsigned int& priority)
{
q_item* new_item = new q_item(item, priority);
if (size == 0) {
start = new_item;
end = new_item;
}
else {
q_item* tmp = end;
while (tmp->priority > priority && tmp != start)
tmp = tmp->prev;
if (tmp != start || start->priority <= priority) {
new_item->next = tmp->next;
if (new_item->next != nullptr)
new_item->next->prev = new_item;
tmp->next = new_item;
new_item->prev = tmp;
if (tmp == end)
end = new_item;
}
else {
new_item->next = start;
start->prev = new_item;
start = new_item;
}
}
++size;
}
void pop_front()
{
if (size == 0)
return;
/*T ret = start->data;*/
q_item* tmp = start;
if (size > 1) {
start->next->prev = nullptr;
start = start->next;
}
else {
start = nullptr;
end = nullptr;
}
delete tmp;
--size;
return;
}
T pop_back()
{
if (size == 0)
return NULL;
T ret = end->data;
q_item* tmp = end;
if (size > 1) {
end->prev->next = nullptr;
end = end->prev;
}
else {
start = nullptr;
end = nullptr;
}
delete tmp;
--size;
return ret;
}
T operator [] (int position) {
q_item* ret = start;
for (int i = 0; i < position && i < size; ++i)
ret = ret->next;
return ret->data;
}
int Size() {
return size;
}
};
#endif