定义
队列(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>