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;
}
下一篇:十字鏈表學習
下下一篇:二叉樹