您的位置:首页 > 理论基础 > 数据结构算法

数据结构与算法-队列

2017-09-29 01:19 295 查看
队列:队列与栈不同,它是一种先进先出的结构

实现

1、数组

2、链表

记录的数据

1、队首位置:第一个元素的位置

2、队尾位置:最后一个元素的位置

3、队列大小:size



队列操作

entryQueue():入队
exitQueue():出队
isQueueEmpty():队列为空
isQueueFull():队列满


队列的实现(顺序数组的实现)

将队列的定义放在queue.h中

class queue
{
private:
int size;
int* a;
int head;
int tail;
public:
queue();
~queue();
bool isQueueEmpty();
bool isQueueFull();
void entryQueue();
int exitQueue();
int getSize()
}


队列的具体实现:

#include<queue.h>
queue::queue(int size)
{
a = new int[size];
this->size = size;
head=0;
tail=0;
}
queue::~queue()
{
delete[] a;
}
bool queue::isQueueEmpty()
{
return (head == tail);
}
bool queue::isQueueFull()
{
return tail+1 == size
}
void queue::entryQueue(int item)
{
if(isQueueFull())
print("the queue is full");
else
{
a[tail ++] = item;
}
}
int queue::exitQueue()
{
if(isQueueEmpty())
print("the queue is empty");
else
{
int result = a[head];
head = head+1;
return result;
}
}
int queue::getSize()
{
return size;
}


上述使用顺序数组的形式实现了队列,但是这种方式有非常大的弊端:当删除队列中的元素时,数组中head之前空间我们无法再次使用,这样就造成了极大的空间浪费。解决的方法是使用循环队列或者直接使用链式存储。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  数据结构