队列

队列

队列:只允许在一端进行插入操作,而另一端进行删除操作的线性表。

允许插入(也称入队、进队)的一端称为队尾,允许删除(也称出队)的一端称为队头。

队列的操作特性:先进先出

一、   
队列的顺序存储结构及实现

通常情况下,队首元素存放在下标为0的一端

队头指针指向队列中的第一个元素之前的元素,队尾指针指向队列中的最后一个元素

队头指针指向队列中的第一个元素,队尾指针指向队列中的最后一个元素的后一个位置

假溢出:当元素被插入到数组中下标最大的位置上之后,队列的空间就用尽了,尽管此时数组的低端还有空闲空间,这种现象叫做假溢出。

循环队列:将存储队列的数组头尾相接

不存在物理的循环结构,用软件方法实现。

求模:rear=(rear+1)% MAXSIZE

front=(front+1)
% MAZSIZE

队空:front==rear

队满:(rear+1) mod QueueSize==front

循环队列类的声明

const int
QueueSize=100;

template

class CirQueue{

public:

CirQueue( );

~ CirQueue( );

void EnQueue(T x);

T DeQueue( );

T GetQueue( );

bool Empty( ){

if (rear==front) return true;

return false;

};

private:

T data[QueueSize];

int front, rear;

};

  1. 循环队列的实现——入队

template

void CirQueue::EnQueue(T x)

{

if ((rear+1) % QueueSize ==front) throw
“上溢”;

rear=(rear+1) % QueueSize;

data[rear]=x;

}

  1. 循环队列的实现——出队

template

T
CirQueue::DeQueue( )

{

if (rear==front) throw “下溢”;

front=(front+1) % QueueSize;

return data[front];

}

2.循环队列的实现——读队头元素

template

T
CirQueue::GetQueue( )

{

if (rear==front) throw “下溢”;

i=(front+1) % QueueSize;

return data[i];

}

  1. 循环队列的实现——队列长度

template

int
CirQueue::GetLength( )

{

if (rear==front) throw “下溢”;

len=(rear-front+ QueueSize) % QueueSize;

return len;

}

二、队列的链接存储结构及实现

链队列类的声明

template

class LinkQueue

{

public:

LinkQueue( );

~LinkQueue( );

void EnQueue(T x);

T DeQueue( );

T GetQueue( );

bool Empty( );

private:

Node *front, *rear;

};

  1. 链队列的实现——构造函数

template

LinkQueue::LinkQueue(
)

{

front=new Node;

front->next=NULL;

rear=front;

}

2.链队列的实现——入队

template

void
LinkQueue::EnQueue(T x)

{

s=new Node;

s->data=x;

s->next=NULL;

rear->next=s;

rear=s;

}

  1. 链队列的实现——出队

template

T
LinkQueue::DeQueue( )

{

if (rear==front) throw “下溢”;

p=front->next;

x=p->data;

front->next=p->next;

delete p;

if (front->next==NULL) rear=front;

return x;

}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值