結論:對帶頭節(jié)點的鏈隊列進行操作更加方便躬贡。
- 不帶頭結點的鏈隊列在入隊第一個元素時需要特殊處理擂仍;
先判斷是否為空肃廓,再選擇插入方式,而帶頭結點則不需要這步操作合溺;
分析如下:
-
鏈式隊列的存儲類型可描述為:
typedef struct {
ElemType data;
strcut LinkNode *next;
} LinkNode;
typedef struct {
LinkNode *front;
LinkNode *rear;
} LinkQueue;
1.帶頭節(jié)點的鏈式隊列
/* with a head node */
/* initialize the queue */
void InitQueue(LinkNode *Q)
{
/* creat a head node */
Q->front = Q->rear = (LinkNode*)malloc(sizeof(LinkNode));
Q->front->next = NULL;
}
/* judge whether the queue is empty */
bool IsEmpty(LinkNode *Q)
{
if (Q->front == Q->rear) return true;
else return false;
}
/* Push a element into the queue */
void EnQueue(LinkQueue *Q, ElemType x)
{
LinkNode *S;
S = (LinkNode*)malloc(sizeof(LinkNode));
S->data = x;
S->next = NULL;
Q->rear->next = S;
Q->rear = S;
}
/* Pop a element from the queue */
bool DeQueue(LinkNode *Q, ElemType *x)
{
if (IsEmpty(Q)) return false;
P = (LinkNode)malloc(sizeof(LinkNode));
P = Q->front->next;
*x = P->data;
Q->front->next = P->next;
if (Q->rear == P)
Q->rear = Q->front;
free(P);
return true;
}
2.不帶頭結點的鏈式隊列
/* with no head node */
/* initialize the queue */
void InitQueue(LinkNode *Q)
{
Q->front = Q->rear = NULL;
}
/* judge whether the queue is empty */
bool IsEmpty(LinkNode *Q)
{
if (Q->front == NULL) return true;
else return false;
}
/* Push a element into the queue */
void EnQueue(LinkQueue *Q, ElemType x)
{
LinkNode *S;
S = (LinkNode*)malloc(sizeof(LinkNode));
S->data = x;
S->next = NULL;
if (IsEmpty(Q)) {
Q->front = Q->rear = S;
} else {
Q->rear->next = S;
Q->rear = S;
}
return;
}
/* Pop a element from the queue */
bool DeQueue(LinkNode *Q, ElemType *x)
{
if (IsEmpty(Q)) return false;
P = (LinkNode)malloc(sizeof(LinkNode));
P = Q->front;
*x = P->data;
if (Q->front == Q->rear) Q->front = Q->rear = NULL;
else {
Q->front = P->next;
}
free(P);
return true;
}