目录
1基本操作编辑
插入新元素,使用PASCAL语言:
1
2
3
4
5
6
7
8
|
procedure
Add2(
var
q:equeue; x:qtype;
var
r:
integer
);
begin
t=r
mod
m+
1
;
if
t=f
then
writeln
(
'full'
)
else
begin
r=t;q[r]=x;
end
;
end
;
|
过程DEL2(Q,Y,F)从循环队列q中取出队首元素
1
2
3
4
5
6
7
|
procedure
del2(
var
q:equeue;
var
y:qtype;
var
f:
integer
);
begin
if
f=r
then
writeln
(
'empty'
)
else
begin
f=f
mod
m+
1
;y=q[f];
end
;
end
;
|
2条件处理编辑
循环队列中,由于入队时尾指针向前追赶头指针;出队时头指针向前追赶尾指针,造成队空和队满时头尾指针均相等。因此,无法通过条件front==rear来判别队列是"空"还是"满"。
解决这个问题的方法至少有两种:
① 另设一
布尔变量以区别队列的空和满;
②另一种方式就是
数据结构常用的: 队满时:(rear+1)%n==front,n为队列长度(所用
数组大小),由于rear,front均为所用空间的指针,循环只是逻辑上的循环,所以需要求余运算。如图情况,队已满,但是rear(5)+1=6!=front(0),对空间长度求余,作用就在此6%6=0=front(0)。
3类型定义编辑
1
2
3
4
5
6
7
8
|
#define QueueSize 100 //应根据具体情况定义该值
typedef
char
DataType;
//DataType的类型依赖于具体的应用
typedef
struct
{
int
front;
//头指针,队非空时指向队头元素
int
rear;
//尾指针,队非空时指向队尾元素的下一位置
int
count;
//计数器,记录队中元素总数
DataType data[QueueSize];
}CirQueue;
|
4基本运算编辑
用第三种方法,循环队列的六种基本运算:
① 置队空
1
2
3
4
5
|
void
InitQueue(CirQueue *Q)
{
Q->front=Q->rear=0;
Q->count=0;
//计数器置0
}
|
② 判队空
1
2
3
4
|
int
QueueEmpty(CirQueue *Q)
{
return
Q->count==0;
//队列无元素为空
}
|
③ 判队满
1
2
3
4
|
int
QueueFull(CirQueue *Q)
{
return
Q->count==QueueSize;
//队中元素个数等于QueueSize时队满
}
|
④ 入队
1
2
3
4
5
6
7
8
|
void
EnQueue(CirQueue *Q,DataType x)
{
if
(QueueFull(Q))
Error(
"Queue overflow"
);
//队满上溢
Q->count ++;
//队列元素个数加1
Q->data[Q->rear]=x;
//新元素插入队尾
Q->rear=(Q->rear+1)%QueueSize;
//循环意义下将尾指针加1
}
|
⑤ 出队
1
2
3
4
5
6
7
8
9
10
|
DataType DeQueue(CirQueue *Q)
{
DataType temp;
if
(QueueEmpty(Q))
Error(
"Queue underflow"
);
//队空下溢
temp=Q->data[Q->front];
Q->count--;
//队列元素个数减1
Q->front=(Q->front+1)%QueueSize;
//循环意义下的头指针加1
return
temp;
}
|
⑥取队头元素
1
2
3
4
5
6
|
DataType QueueFront(CirQueue *Q)
{
if
(QueueEmpty(Q))
Error(
"Queue is empty."
);
return
Q->data[Q->front];
}
|
````````````````````````````````````````````````````````````````````````````````````
队列的操作特点是“先进先出”。前者主要是头指针、尾指针的使用,后者主要是理解循环队列提出的原因及其特点。两者都要掌握队列空与满的判定条件以及出队列、入队列操作的实现。