现在的位置: 首页 > 综合 > 正文

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

2018年04月29日 ⁄ 综合 ⁄ 共 1302字 ⁄ 字号 评论关闭
#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;
}

【上篇】
【下篇】

抱歉!评论已关闭.