数据结构 C 语言实现系列 [4] —— 队列 [1]
#include <stdio.h>
#include <stdlib.h>
typedef int elemType;
/************************************************************************/
/* 以下是关于队列链接存储操作的 6 种算法 */
/************************************************************************/
struct sNode{
elemType data; /* 值域 */
struct sNode *next; /* 链接指针 */
};
struct queueLK{
struct sNode *front; /* 队首指针 */
struct sNode *rear; /* 队尾指针 */
};
/* 1. 初始化链队 */
void initQueue( struct queueLK *hq)
{
hq->front = hq->rear = NULL; /* 把队首和队尾指针置空 */
return;
}
/* 2. 向链队中插入一个元素 x */
void enQueue(struct queueLK *hq, elemType x)
{
/* 得到一个由 newP 指针所指向的新结点 */
struct sNode *newP;
newP = malloc( sizeof(struct sNode));
if (newP == NULL){
printf(" 内存空间分配失败! ");
exit(1);
}
/* 把 x 的值赋给新结点的值域,把新结点的指针域置空 */
newP->data = x;
newP->next = NULL;
/* 若链队为空,则新结点即是队首结点又是队尾结点 */
if (hq->rear == NULL){
hq->front = hq->rear = newP;
} else{ /* 若链队非空,则依次修改队尾结点的指针域和队尾指针,使之指向新的队尾
结点 */
hq->rear = hq->rear->next = newP; /* 注意赋值顺序哦 */
}