基本操作:
入队(enqueue):队尾rear插入
出队(dequeue):队首front删除
实现方式
链表实现:继承自链表结构(本文略)
数组实现:循环数组,只要Rear或者Front达到数组的尾端,他就绕回到开头。
#include <iostream>
using namespace std;
typedef struct QueueRecord
{
int m_capacity;
int m_rear;
int m_front;
int m_size;
int* m_arry;
}*Queue;
Queue CreatQueue(int capacity);
void Enqueue(Queue q, int x);
void Dequeue(Queue q);
bool IsFull(Queue q);
bool IsEmpty(Queue q);
void Traverse(Queue q);//队首到队尾遍历
bool IsMakeEmpty(Queue q);
int main()
{
Queue q = CreatQueue(5);
Enqueue(q, 1);
Enqueue(q, 2);
Enqueue(q, 3);
Traverse(q);
cout << "出队一次:" << endl;
Dequeue(q);
Traverse(q);
cout << "将4入队:" << endl;
Enqueue(q, 4);
Traverse(q);
if (IsMakeEmpty(q))
cout << "置空成功" << endl;
Traverse(q);
system("pause");
return 0;
}
Queue CreatQueue(int capacity)
{
Queue q = new QueueRecord;
q->m_capacity = capacity;
q->m_rear = -1;
q->m_front = -1;
q->m_size = 0;
q->m_arry = new int[capacity];
return q;
}
void Enqueue(Queue q, int x)
{
if (!IsFull(q))
{
q->m_size++;
q->m_rear++;
q->m_arry[q->m_rear] = x;
}
else
cout << "队列已满,无法入队" << endl;
}
void Dequeue(Queue q)
{
if (!IsEmpty(q))
{
q->m_size--;
q->m_front++;
q->m_rear--;
}
else
cout << "队列以空,无法出队" << endl;
}
bool IsFull(Queue q)
{
if (q->m_size == q->m_capacity)
return true;
return false;
}
bool IsEmpty(Queue q)
{
if (q->m_size == 0)
return true;
return false;
}
void Traverse(Queue q)
{
cout << "队首到队尾遍历:" << endl;
if (!IsEmpty(q))
{
int tmp = q->m_size;
int i = 0;
while (i < tmp)
{
cout << q->m_arry[i] << " ";
i++;
}
cout << endl;
}
else
cout << "队列为空" << endl;
}
bool IsMakeEmpty(Queue q)
{
if (q != nullptr)
{
q->m_size = 0;
q->m_front = -1;
q->m_rear = -1;
return true;
}
else
cout << "不占空间的空栈" << endl;
}
应用:
1、作业送交给打印机;但是打印机可以删除中间的队列,违反了队列的严格定义
但是,放到队列未必最好,有时希望花费时间最长的作业放到最后,此时可以使用堆(优先队列)。
2、PC机的网络设置,磁盘是放在一台叫做文件服务器的机器上,用户是根据先到先使用的原则访问文件,其数据结构为队列
3、接线员对大公司的传呼
4、在终端上的等待也是队列
拓展
排队论:处理这样一类问题,用概率的方法计算用户排队预计等待时间,以及整个队列能够容纳的处理时间。
答案依赖于用户加入队列的概率,以及加入队列后处理服务花费的时间,这两个参数作为概率分布函数给出。