<pre code_snippet_id="1954965" snippet_file_name="blog_20161028_1_5985205" name="code" class="cpp">//头文件如下
#ifndef QUEUE_H
#define QUEUE_H
#include<iostream>
template<class T>
class Queue
{
private:
struct Node
{
T item;
Node *next;
};
Node *head = NULL;
Node *tail = NULL;
int N = 0; //记录队列中有多少元素
public:
Queue(){};
bool isEmpty() {return head == NULL;};
int size() {return N;};
void push(T t);
T pop();
~Queue();
};
template<class T>
void Queue<T>::push(T t)
{
Node *n = new Node;
n->item = t;
n->next = NULL;
if(isEmpty())
head = tail = n;
else{
tail->next = n;
tail = n;
}
N++;
}
template<class T>
T Queue<T>::pop()
{
T result = head->item;
Node *d = head;
head = head->next;
N--;
if(isEmpty())
tail = NULL;
delete d; // 注意避免内存泄漏
return result;
}
template<class T>
Queue<T>::~Queue()
{
while(!isEmpty()) //通过遍历每个节点的方式来删除节点
{
Node *n = head;
head = head->next;
N--;
delete n;
}
tail = NULL; // 记得将尾节点设置为空
}#endif