#pragma once
#include "stdio.h"
namespace SF
{
template<class T>
struct QueueNode
{
T data;
QueueNode<T> *next;
QueueNode()
{
this->next = nullptr;
}
};
//链队列
template<class T>
class Queue
{
public:
Queue();
~Queue();
void Enqueue(T val);
QueueNode<T> *Dequeue();
int Size() { return this->count; };
void Show();
void Release() { this->ReleaseQueue(head); };
bool IsEmtpy() { return this->count > 0; };
private:
int count;
QueueNode<T> *head;
QueueNode<T> *tail;
void ReleaseQueue(QueueNode<T> *node);
};
template<class T>
Queue<T>::Queue()
{
this->count = 0;
this->head = new QueueNode<T>();
this->tail = this->head;
}
template<class T>
Queue<T>::~Queue()
{
Release();
}
template<class T>
void Queue<T>::Enqueue(T val)
{
QueueNode<T> *node = new QueueNode <T>();
node->data = val;
//尾巴进队
if (!head->next)
{
head->next = node;
tail = node;
}
else
{
tail->next = node;
tail = node;
}
this->count++;
}
template<class T>
QueueNode<T>* Queue<T>::Dequeue()
{
//头部出队
QueueNode<T> *node = head->next;
if (node)
{
head->next = node->next;
this->count--;
}
return node; //这里要返回就不使用delete 了 外部使用完毕需要释放
}
template<class T>
void Queue<T>::Show()
{
this->tail = this->head->next;
while (tail)
{
printf("%i\n", tail->data);
tail = tail->next;
}
}
template<class T>
void Queue<T>::ReleaseQueue(QueueNode<T> *node)
{
if (node)
{
ReleaseQueue(node->next);
delete node;
}
}
}
网友评论