C++链表实现队列

//queue.hpp

#pragma once

#include 

using namespace std;

template <class T>
class Node
{
public:
	Node<T>* next;
	T data;
};

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

	bool isEmpty();
	int size();
	void enqueue(T t);//插入元素
	T dequeue();//取出元素

private:
	Node<T>* head;
	Node<T>* tail;
	int length;
};

template<class T>
Queue<T>::Queue()
{
	this->head = new Node<T>;
	head->next = NULL;
	this->tail = NULL;
	length = 0;
}

template<class T>
Queue<T>::~Queue()
{

}

template<class T>
bool Queue<T>::isEmpty()
{
	return size() == 0;
}

template<class T>
int Queue<T>::size()
{
	return length;
}

template<class T>
void Queue<T>::enqueue(T t)//插入元素(尾插)
{
	if (tail == NULL)
	{
		tail = new Node<T>;
		tail->data = t;
		tail->next = NULL;
		head->next = tail;
	}
	else
	{
		Node<T>* pTail = tail;
		tail = new Node<T>;
		tail->data = t;
		pTail->next = tail;
		tail->next = NULL;
	}
	length++;
}

template<class T>
T Queue<T>::dequeue()
{
	if (isEmpty())
	{
		return NULL;
	}
	T data = head->next->data;
	Node<T>* pCurr = head->next;
	head->next = pCurr->next;
	delete pCurr;
	if (isEmpty())
	{
		tail = NULL;
	}
	length--;

	return data;
}
queue.hpp
//队列

#include 

#include "queue.hpp"

using namespace std;

//用链表实现队列

int main()
{
    Queue<int> aqueue;
    aqueue.enqueue(10);
    aqueue.dequeue();
    system("pause");
    return 0;
}

你可能感兴趣的:(C++链表实现队列)