主要是想联系一下c++中的模板怎么使用,随便复习一下队列。队列最基本的数据结构元素先进先出,这些就不多说了。注意:写程序时copy构造函数和copy赋值函数的写法。
#include<iostream>
#include<string>
using namespace std;
template<class Type>
class QueueItem
{
public :
QueueItem()
{}
QueueItem(const Type &t) : data(t), next(0)
{}
Type data;
QueueItem *next;
};
template<class Type>
class Queue
{
public:
Queue():head(0), tail(0)
{}
Queue(const Queue &q):head(0),tail(0)
{
copy_element(q);
}
Type front() const;
void pop();
void push(const Type &);
Queue & operator=(const Queue &);
bool IsEmpty() const
{
return head == 0;
}
~Queue()
{
destroy();
}
private:
QueueItem<Type> *head;
QueueItem<Type> *tail;
void destroy();
void copy_element(const Queue &);
};
template<class Type> Type Queue<Type>::front() const
{
return head->data;
}
template<class Type> void Queue<Type>::pop()
{
QueueItem<Type> *h = head;
head = head->next;
delete h;
h = 0;
}
template<class Type> void Queue<Type>::push(const Type &t)
{
QueueItem<Type> *item = new QueueItem<Type>(t);
if (head == 0) {
head = tail = item;
} else {
tail->next = item;
tail = item;
}
}
template<class Type> void Queue<Type>::destroy()
{
while (!IsEmpty())
pop();
}
template<class Type> void Queue<Type>::copy_element(const Queue &q)
{
QueueItem<Type> *h = q.head;
while (h != 0) {
push(h->data);
h = h->next;
}
}
template<class Type> Queue<Type>& Queue<Type>::operator=(const Queue &q)
{
destroy();
copy_element(q);
return *this;
}