队列的基本操作——链式队列的类模板定义

62 篇文章 0 订阅
43 篇文章 0 订阅

定义
     队列(Queue)是只允许在一端进行插入,而在另一端进行删除的运算受限的线性表
  (1)允许删除的一端称为队头(Front)。
  (2)允许插入的一端称为队尾(Rear)。
  (3)当队列中没有元素时称为空队列。
  (4)队列亦称作先进先出(First In First Out)的线性表,简称为FIFO表。
     队列的修改是依先进先出的原则进行的。新来的成员总是加入队尾(即不允许"加塞"),每次离开的成员总是队列头上的(不允许中途离队),即当前"最老的"成员离队。
 【例】在队列中依次加入元素a1,a2,…,an之后,a1是队头元素,an是队尾元素。退出队列的次序只能是a1,a2,…,an

 

"Queue.h"

<span style="font-size:18px;color:#000000;">#pragma once
#include <iostream>
using namespace std;
#include "assert.h"

typedef int DataType;

template<class T>
struct Node
{
	DataType _data;
	struct Node<T>* _next;

	Node(const T& data)
		:_data(data)
		,_next(NULL)
	{}
};

template<class T>
class Queue
{
public:
	Queue()//构造函数
		:_head(NULL)
		,_tail(NULL)
		,_size(0)
	{}

	~Queue()//析构函数
	{
		if (_head)
		{
			delete _head;
		}
		if (_tail)
		{
			delete _tail;
		}
	}

	void Push(const T& data)//入队
	{
		if (_head == NULL)
		{
			_head = _tail = new Node<T> (data);
		} 
		else
		{
			_tail->_next = new Node<T> (data);
			_tail = _tail->_next;
		}
		++_size;
	}

	void Pop()//出队
	{
		if (Empty() == true)
		{
			printf("Queue is Empty\n");
			return;
		} 
		else
		{
			Node<T>* del = _head;
			_head = _head->_next;
			delete del;
		}
		--_size;
	}

	void PrintQueue()//打印队列
	{
		if (Empty() == true)
		{
			return;
		}
		Node<T>* pNode = NULL;
		pNode = _head;

		while(pNode != _tail)
		{
			cout<<pNode->_data<<" ";
			pNode = pNode->_next;
		}
		cout<<pNode->_data<<endl;
	}

	T& Front()//返回队列的对头元素
	{
		//assert(_head);
		return _head->_data;
	}

	T& Back()//返回队列的队尾元素
	{
		//assert(_tail);
		return _tail->_data;
	}

protected:
	bool Empty()//判断队列是否为空
	{
		return _size == 0;
	}

	size_t Size()//队列的长度
	{
		return _size;
	}

private:
	Node<T>* _head;//队头指针
	Node<T>* _tail;//队尾指针
	size_t _size;//队列长度
};

</span>


 

"test.cpp"

 

<span style="font-size:18px;color:#000000;">#define _CRT_SECURE_NO_WARNINGS 1
#include "queue.h"

void test()
{
	Queue<int> queue;
	queue.Push(1);
	queue.Push(4);
	queue.Push(7);
	queue.Push(9);
	queue.PrintQueue();

	queue.Pop();
	queue.Pop();
	queue.PrintQueue();

	int ret = queue.Back()-queue.Front();
	cout<<ret<<endl;
}

int main()
{
	test();
	system("pause");
	return 0;
}</span>



 

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值