队列的定义
队列是只允许在一端进行插入操作,在另一端进行删除操作的线性表。插入的一端称为队尾,删除的一端称为队头。
队列具有“先进先出”的特性,如下图所示:
队列的顺序存储结构及其实现
- 设置队头队尾指针,减少时间开销。
- 采用循环队列,解决假溢出问题。
队空和队满的判定问题
初始化空队时,令front = rear = 0 ,
当队空时:front = rear。
当队满时:front = rear 也成立。
因此只凭等式 front = rear 无法判断队空还是队满。 可以这样处理:
少用一个元素空间,即以“队列头指针front在队尾指针rear的下一个位置上”作为队列“满”状态的标志。
队空时: front = rear
队满时: (rear+1) % QueueSize = front
图片来自百度
#include <iostream>
using namespace std;
/*
队列的顺序存储
*/
const int QueueSize = 100; //定义存储队列元素的数组的最大长度
template < class T >
class CirQueue
{
private:
T data[QueueSize];
int front; //队头指针
int rear; //队尾指针
public:
CirQueue()
{
front = rear = 0;
}
~CirQueue() {}
void EnQueue(T x) //入队操作
{
if((rear + 1) % QueueSize == front)
cout << "上溢";
else
{
rear = (rear + 1) % QueueSize;
}
data[rear] = x;
}
T DeQueue() //出队操作
{
if(rear == front)
cout << "下溢";
front = (front + 1) % QueueSize;
return data[front];
}
T GetQueue()
{
if(rear == front)
cout << "下溢";
int i = (front + 1) % QueueSize; //注意不要给队头指针赋值
return data[i];
}
int Empty()
{
if(front == rear)
return 1;
else
return 0;
}
};
int main()
{
CirQueue<int> cirQueue;
cirQueue.EnQueue(7);
cirQueue.EnQueue(1);
cirQueue.EnQueue(2);
cirQueue.EnQueue(3);
cirQueue.EnQueue(4);
cirQueue.EnQueue(5);
cirQueue.EnQueue(6);
cirQueue.DeQueue();
cout << cirQueue.GetQueue();
}
队列的链接存储结构
链队列是在单链表的基础上做了简单的修改,所以没什么好说的。
直接上代码吧
#include<iostream>
#define maxSize 20
using namespace std;
struct Node
{
int data;
Node * next;
};
class LinkQueue
{
public:
LinkQueue();
~LinkQueue();
void EnQueue(int x);
int DeQueue();
int GetQueue();
bool isEmpty();
private:
Node * front, * rear;
};
Node * s = NULL;
LinkQueue::LinkQueue()
{
s = new Node;
s->next = NULL;
front = rear = s;
}
LinkQueue::~LinkQueue()
{
delete front;
delete rear;
}
void LinkQueue::EnQueue(int x)
{
s = new Node;
s->data = x;
s->next = NULL;
rear->next = s;
rear = s;
}
int LinkQueue::DeQueue()
{
if(rear == front)
{
cout << "下溢";
return 0;
}
else
{
s = front->next;
int x = s->data;
front->next = s->next;
if(s->next == NULL)
rear = front;
return x;
}
}
int LinkQueue::GetQueue()
{
return front->next->data;
}
bool LinkQueue::isEmpty()
{
return front == rear ? true : false;
}
int main()
{
LinkQueue linkQueue;
linkQueue.EnQueue(1);
linkQueue.EnQueue(2);
linkQueue.EnQueue(3);
linkQueue.EnQueue(4);
linkQueue.EnQueue(5);
linkQueue.EnQueue(6);
linkQueue.DeQueue();
cout << linkQueue.GetQueue();
}