108 lines
1.8 KiB
C++
108 lines
1.8 KiB
C++
// Copyright (C) 2007 EQ2EMulator Development Team - GPL v3+ License
|
|
|
|
#pragma once
|
|
|
|
template<class T>
|
|
class MyQueue;
|
|
|
|
template<class T>
|
|
class MyQueueNode
|
|
{
|
|
public:
|
|
// Constructor - initializes node with given data pointer
|
|
MyQueueNode(T* data)
|
|
{
|
|
next = nullptr;
|
|
this->data = data;
|
|
}
|
|
|
|
friend class MyQueue<T>;
|
|
|
|
private:
|
|
T* data; // Pointer to the data stored in this node
|
|
MyQueueNode<T>* next; // Pointer to the next node in the queue
|
|
};
|
|
|
|
template<class T>
|
|
class MyQueue
|
|
{
|
|
public:
|
|
// Constructor - initializes empty queue
|
|
MyQueue()
|
|
{
|
|
head = tail = nullptr;
|
|
}
|
|
|
|
// Destructor - cleans up all nodes and their data
|
|
~MyQueue()
|
|
{
|
|
clear();
|
|
}
|
|
|
|
// Adds a new element to the back of the queue
|
|
void push(T* data)
|
|
{
|
|
if (head == nullptr) {
|
|
tail = head = new MyQueueNode<T>(data);
|
|
} else {
|
|
tail->next = new MyQueueNode<T>(data);
|
|
tail = tail->next;
|
|
}
|
|
}
|
|
|
|
// Removes and returns the front element from the queue
|
|
T* pop()
|
|
{
|
|
if (head == nullptr) {
|
|
return nullptr;
|
|
}
|
|
|
|
T* data = head->data;
|
|
MyQueueNode<T>* next_node = head->next;
|
|
delete head;
|
|
head = next_node;
|
|
|
|
return data;
|
|
}
|
|
|
|
// Returns the front element without removing it from the queue
|
|
T* top()
|
|
{
|
|
if (head == nullptr) {
|
|
return nullptr;
|
|
}
|
|
|
|
return head->data;
|
|
}
|
|
|
|
// Returns true if the queue is empty
|
|
bool empty()
|
|
{
|
|
return head == nullptr;
|
|
}
|
|
|
|
// Removes all elements from the queue and deletes their data
|
|
void clear()
|
|
{
|
|
T* d = nullptr;
|
|
while ((d = pop())) {
|
|
delete d;
|
|
}
|
|
}
|
|
|
|
// Returns the number of elements in the queue
|
|
int count()
|
|
{
|
|
int count = 0;
|
|
MyQueueNode<T>* d = head;
|
|
while (d != nullptr) {
|
|
count++;
|
|
d = d->next;
|
|
}
|
|
return count;
|
|
}
|
|
|
|
private:
|
|
MyQueueNode<T>* head; // Pointer to the first node in the queue
|
|
MyQueueNode<T>* tail; // Pointer to the last node in the queue
|
|
}; |