鏈式隊列指的是使用鏈表來實現(xiàn)的隊列杖小,操作比較簡單
- 定義一個鏈式隊列以及相關宏定義
#define OK 1
#define ERROR 0
#define TRUE 1
#define FALSE 0
#define MAXSIZE 20 /* 存儲空間初始分配量 */
typedef int Status;
typedef int QElemType; /* QElemType類型根據(jù)實際情況而定坏快,這里假設為int */
typedef struct QNode /* 結點結構 */
{
QElemType data;
struct QNode *next;
}QNode,*QueuePtr;
typedef struct /* 隊列的鏈表結構 */
{
QueuePtr front,rear; /* 隊頭挨厚、隊尾指針 */
}LinkQueue;
- 初始化隊列
創(chuàng)建一個頭結點并且將將隊列的頭尾指針指向該結點
Status InitLinkQueue(LinkQueue *Q){
//1. 頭/尾指針都指向新生成的結點
Q->front = Q->rear = (QueuePtr)malloc(sizeof(QNode));
//2.判斷是否創(chuàng)建新結點成功與否
if (!Q->front) {
return ERROR;
}
//3.頭結點的指針域置空
Q->front->next = NULL;
return OK;
}
- 銷毀隊列:遍歷整個隊列將遍歷的結點free
Status DestoryQueue(LinkQueue *Q){
//遍歷整個隊列,銷毀隊列的每個結點
while (Q->front) {
//Q->rear在這個相當于一個臨時變量temp
Q->rear = Q->front->next;
free(Q->front);
Q->front = Q->rear;
}
return OK;
}
- 將隊列Q置空(清空完成后還能夠插入數(shù)據(jù))
Status ClearQueue(LinkQueue *Q){
QueuePtr p,q;
Q->rear = Q->front;
p = Q->front->next;
Q->front->next = NULL;
while (p) {
q = p;
p = p->next;
free(q);
}
return OK;
}
- 判斷隊列是否為空
Status QueueEmpty(LinkQueue Q){
if (Q.front == Q.rear)
return TRUE;
else
return FALSE;
}
- 獲取隊列長度
int QueueLength(LinkQueue Q){
int i= 0;
QueuePtr p;
p = Q.front;
while (Q.rear != p) {
i++;
p = p->next;
}
return i;
}
-
入隊列:插入元素e為隊列Q的新元素
- 為入隊元素分配結點空間,用指針s指向;
- 將新結點s指定數(shù)據(jù)域.
- 將新結點插入到隊尾
- 修改隊尾指針
Status EnQueue(LinkQueue *Q,QElemType e){
//為入隊元素分配結點空間,用指針s指向;
QueuePtr s = (QueuePtr)malloc(sizeof(QNode));
//判斷是否分配成功
if (!s) {
return ERROR;
}
//將新結點s指定數(shù)據(jù)域.
s->data = e;
s->next = NULL;
//將新結點插入到隊尾
Q->rear->next = s;
//修改隊尾指針
Q->rear = s;
return OK;
}
-
出隊列
- 第一步:判斷隊列是否為空;
- 第二步:要刪除的隊頭結點暫時存儲在p
- 第三步:要刪除的隊頭結點的值賦值給e
- 第四步:原隊列頭結點的后繼p->next 賦值給頭結點后繼
- 第五步:若隊頭就是隊尾,則刪除后將rear指向頭結點
- 第六步:free出隊的數(shù)據(jù)結點
Status DeleteQueue(LinkQueue *Q,QElemType *e){
QueuePtr p;
//判斷隊列是否為空;
if (Q->front == Q->rear) {
return ERROR;
}
//將要刪除的隊頭結點暫時存儲在p
p = Q->front->next;
//將要刪除的隊頭結點的值賦值給e
*e = p->data;
//將原隊列頭結點的后繼p->next 賦值給頭結點后繼
Q->front->next = p ->next;
//若隊頭就是隊尾,則刪除后將rear指向頭結點.
if(Q->rear == p) Q->rear = Q->front;
free(p);
return OK;
}