C++实现队列(链表版)

#include <iostream>
using namespace std;

template<typename T> class myQueue;

template<typename T>
class node
{
	friend class myQueue<T>;
	node(const T& t) : data(t), next(0)
	{
	} 
	T data;
	node *next;
};

template<typename T>
class myQueue
{
public:
	myQueue() : head(0), tail(0), length(0)
	{
	}
	~myQueue()
	{
		destroy();
	}
	bool empty() const
	{
		//return length == 0;
		return head == 0;
	}
	
	void push(const T&);
	T& front() const;
	void pop();
	int getLen() const;
	
private:
	void destroy();
	node<T> *head, *tail;
	int length;
};


template<typename T>
void myQueue<T>::push(const T& val)
{
	node<T> *p = new node<T>(val);
	
	if(empty())
		head = tail = p;
	else
	{
		tail->next = p;
		tail = p;
	}
	length++;
}

template<typename T>
T& myQueue<T>::front() const
{
	return head->data;	
}

template<typename T>
void myQueue<T>::pop()
{
	if(empty())
	{
		cout << "empty" << endl;
		return;
	}	
	else
	{
		node<T> *p = head;
		head = head->next;
		delete p;
		length--;
	}
}

template<typename T>
void myQueue<T>::destroy()
{
	while(!empty())
	{
		pop();
		length--;
	}
}

template<typename T>
int myQueue<T>::getLen() const
{
	return length;	
}

int main(void)
{
//	myQueue<int> q;
	
//	q.push(1);
//	q.push(2);
//	q.push(3);
//	q.push(4);
//	q.push(5);

//	myQueue<double> q;
//	q.push(1.1);
//	q.push(2.2);
//	q.push(3.3);
//	q.push(4.4);
//	q.push(5.5);

	myQueue<string> q;
	q.push("la");
	q.push("lalala");
	q.push("hehe");
	q.push("hoho");
	q.push("get it");
	
	while(!q.empty())
	{
		int len = q.getLen();
		cout << "queue length: " << len << endl;
		cout << "front: ";
		cout << q.front() << endl;
		q.pop();
	}

	return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值