【c++版数据结构】链队列的实现

和线性表的单链表一样,为了操作方便,实现代码中链队列拥有一个头结点

该链队列:包含头指针尾指针

代码如下:

#pragma once

#include<iostream>
#include<cstdlib>
#include<cassert>
using namespace std;

template<class T>
class Queue;

template<class T>
class QNode
{
	friend Queue<T>;
private:
	T _data;
	QNode<T> *_next;
public:
	QNode(T data = T(), QNode<T> *next = NULL) :_data(data), _next(next){}
};

template<class T>
class Queue
{
private:
	QNode<T> *front;
	QNode<T> *rear;
public:
	explicit Queue();
	virtual ~Queue();
	void push(const T& value);
	void pop();
	bool empty()const;
	size_t size()const;
	T &top();
	const T& top()const;
	void destory();
	void clear();
};

template<class T>
Queue<T>::~Queue()
{
	destory();
}

template<class T>
void Queue<T>::destory()
{
	clear();
	delete front;
	front = NULL;
	rear = NULL;
}

template<class T>
void Queue<T>::clear()
{
	QNode<T> *tmp = front->_next;
	while (tmp != NULL)
	{
		front->_next = tmp->_next;
		delete tmp;
		tmp = front->_next;
	}
}

template<class T>
const T& Queue<T>::top()const
{
	assert(empty() == false);
	return front->_next->_data;
}

template<class T>
T& Queue<T>::top()
{
	assert(empty() == false);
	return front->_next->_data;
}

template<class T>
 Queue<T>::Queue()
{
	front = rear = new QNode<T>;
}

template<class T>
void Queue<T>::push(const T& value)
{
	QNode<T> *tmp = new QNode<T>(value);
	assert(tmp != NULL);
	rear->_next = tmp;
	rear = rear->_next;
}

template<class T>
bool Queue<T>::empty()const
{
	return front == rear;
}

template<class T>
size_t Queue<T>::size()const
{
	size_t size = 0;
	QNode<T> *tmp = front->_next;
	while (tmp != NULL)
	{
		++size;
		tmp = tmp->_next;
	}
	return size;
}

template<class T>
void Queue<T>::pop()
{
	if (empty())
	{
		cout << "it's already empty! can't pop!" << endl;
		return;
	}
	QNode<T> *tmp = front->_next;
	front->_next = tmp->_next;
	delete tmp;
	if (size() == 0)
		rear = front;
}


你可能感兴趣的:(C++,链队列)