C++数据结构——链队列(类模板)

LinkQueue.h:

#pragma once
template <class DataType>
struct Node
{
     
	DataType data;
	Node<DataType>* next;
};

template <class DataType>
class LinkQueue
{
     
private:
	Node<DataType>* front, * rear;
	int length;
public:
	LinkQueue();
	~LinkQueue();
	void enQueue(DataType x);
	bool deQueue(DataType& item);
	bool getFront(DataType& item);
	bool isEmpty();
	void clearQueue();
	void displayQueue();
	int queueLength();
};

typedef LinkQueue<char> CharLinkQueue;

LinkQueue.cpp:

#include "LinkQueue.h"
#include 
using namespace std;

template<class DataType>
inline LinkQueue<DataType>::LinkQueue()
{
     
	Node<DataType>* s = new Node<DataType>;
	s->next = nullptr;
	front = rear = s;
	length = 0;
}

template<class DataType>
inline LinkQueue<DataType>::~LinkQueue()
{
     
	Node<DataType>* p = front;
	while (p)
	{
     
		Node<DataType>* q = p;
		p = p->next;
		delete q;
	}
}

template<class DataType>
inline void LinkQueue<DataType>::enQueue(DataType x)
{
     
	Node<DataType>* s = new Node<DataType>;
	s->next = nullptr;
	s->data = x;
	rear->next = s;
	rear = s;
	length++;
}

template<class DataType>
inline bool LinkQueue<DataType>::deQueue(DataType& item)
{
     
	if (isEmpty()) {
     
		return false;
	}
	else
	{
     
		Node<DataType>* p = front->next;
		item = p->data;
		front->next = p->next;
		if (p->next == nullptr) {
     
			rear = front;
		}
		delete p;
		length--;
		return true;
	}

}

template<class DataType>
inline bool LinkQueue<DataType>::getFront(DataType& item)
{
     
	if (isEmpty()) {
     
		return false;
	}
	else
	{
     
		item = front->next->data;
		return true;
	}
	
}

template<class DataType>
inline bool LinkQueue<DataType>::isEmpty()
{
     
	if (rear == front) {
     
		return true;
	}
	else
	{
     
		return false;
	}
	
}

template<class DataType>
inline void LinkQueue<DataType>::clearQueue()
{
     

}

template<class DataType>
inline void LinkQueue<DataType>::displayQueue()
{
     
	Node<DataType>* p = front;
	while (p != rear)
	{
     
		cout << p->next->data << endl;
		p = p->next;
	}
}

template<class DataType>
inline int LinkQueue<DataType>::queueLength()
{
     
	return length;
}

template class LinkQueue<char>;

int main() {
     
	CharLinkQueue c1;
	c1.enQueue('a');
	c1.enQueue('b');
	cout << c1.queueLength() << endl;
	c1.displayQueue();
	char item;
	c1.deQueue(item);
	cout << item << endl;
	c1.deQueue(item);
	cout << item << endl;
	system("pause");
	return 0;
}

懒猫老师

你可能感兴趣的:(数据结构)