#ifndef QUEUE_HH
#define QUEUE_HH
#include<iostream>
#include<stdlib.h>
using namespace std;
template <typename type>
struct Node
{
type value;
Node *next;
};
template <typename type>
class Queue
{
private:
int len;
Node<type> *head;
Node<type> *tail;
public:
Queue();
~Queue();
bool isEmpty();
type poll();
bool add(type);
int getLength();
};
template <typename type>
Queue<type>::Queue()
{
this->len = -1;
this->head = NULL;
this->tail = NULL;
}
template <typename type>
bool Queue<type>::isEmpty()
{
if(this->len == -1 || this->head == NULL)
{
return true;
}
return false;
}
//in queue
template <typename type>
bool Queue<type>::add(type value)
{
Node<type> *vNode = new Node<type>();
vNode->value = value;
if(vNode == NULL)
{
return false;
}
if(this->len == -1 || this->head == NULL)
{
vNode->next = NULL;
this->head = vNode;
this->tail = vNode;
}
else
{
vNode->next = NULL;
this->tail->next = vNode;
this->tail = vNode;
}
this->len++;
return true;
}
//out of queue
template <typename type>
type Queue<type>::poll()
{
if(this->len == -1 || this->head == NULL)
{
return NULL;
}
type tValue = this->head->value;
Node<type> *tNode = this->head;
this->head = this->head->next;
free(tNode);
tNode = NULL;
this->len--;
return tValue;
}
//get queue length
template <typename type>
int Queue<type>::getLength()
{
return this->len + 1;
}
template <typename type>
Queue<type>::~Queue()
{
while(this->poll()) {}
}
#endif
队列 C++ 适用各种数据类型
最新推荐文章于 2022-10-16 19:57:21 发布