c++ 实现队列

主要是想联系一下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;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值