1 特点
插入在队列头(front)进行,删除在队列尾(rear)进行,简称先进先出(first in first out)
2 数据结构定义
typedef struct
{
int queue[MAXSIZE];
int front;
int rear;
}sequeue;
sequeue *q;
入队列操作
q->queue[++q->rear] = x;
出队列操作
q->front++;
队列长度
q->rear - q->front
队列空条件
q->rear == q->front
队列满条件
q->rear - q->front == MAXSIZE
3、顺序队列缺点
假溢出:当队尾指针到达队尾,而队列还有空间,导致数据无法入队列。
改善:循环队列
4、循环队列
入队列操作
if(q->rear+1 == MAXSIZE)
q->rear = 0;
else
q->rear++;
模运算简单描述
q->rear = (q->rear+1)%MAXSIZE
出队列操作
if(q->front+1 == MAXSIZE)
q->front = 0;
else
q->front++;
eg:q->front = (q->front+1)%MAXSIZE;
队列空和队列满的条件都为
q->rear == q->front;
最好的方法区分空和满
采用少使用区分队列满与空
其他方法:在入队列前测试队尾指针加1是否等于队头指针,相等则为队满,即(q->rear+1)%MAXSIZE == q->front 队满
队列长度
(q->rear - q->front+MAXSIZE)% MAXSIZE;
5 基本运算
(1)初始化
void init_queue(sequeue *q)
{
q->front = 0;
q->rear = 0;
}
(2)入队列
int in_queue(sequeue *q, int x)
{
if((q->rear+1)%MAXSIZE == q->front)
return 0;
else
{
q->rear = (q->rear+1)%MAXSIZE;
q->queue[q->rear] = x;
return 1;
}
}
(3)出队列
int out_queue(sequeue *q)
{
if(q->rear == q->front)//采用少使用区分队列满与空
return NULL;
else
{
q->front = (q->front+1)%MAXSIZE;
return q->queue[q->front];
}
}
(4)读队头元素
int getqueue(sequeue *q)
{
if(q->rear == q->front)
return NULL;
else
return q->queue[(q->front+1)%MAXSIZE];
}
(5)判断队列空
int is_empty_queue(sequeue *q)
{
if(q->rear == q->front)
return 1;
else
return 0;
}
下一篇:十字链表学习
下下一篇:二叉树