链式队列由队列指针,和各个节点组成。链式队列含有头结点。初始化的的代码如下:
int queueinit(Q **q)
{
(*q) = (Q *)malloc(sizeof(Q)); // 先给队列指针分配空间
if((*q) == NULL)
{
return FAILURE;
}
Node *p=(Node *)malloc(sizeof(Node)); //新建一个头结点
if(p == NULL)
{
return FAILURE;
}
p->next = NULL; // 初始化头结点的next指针指向空
(*q)->front = (*q)->rear = p; //初始化头指向尾指向头指针
return SUCCESS;
}
进入队列代码如下:
int queueinsert(Q*queue, int e)
{
if(NULL == queue)
{
return FAILURE;
}
Node *q= (Node *)malloc(sizeof(Node));
if (NULL == q)
{
return FAILURE;
}
q->data = e; //数据域
q->next = NULL; //指针域
queue->rear->next = q;
queue->rear = q; //队尾指针指向新的结点
return SUCCESS;
}
删除节点:队列每次只能从队头节点开始删除,需要注意的是当只有一个节点的时候需要将尾指针指向 头结点。代码如下:
int DeleteQueue(Q *q)
{
if (q == NULL || q->rear == q->front)
{
return FAILURE;
}
int e;
Node *p = q->front->next;
e = p->data;
q->front->next = p->next;
if (!p->next)
{
q->rear = q->front;
}
free(p);
return e;
}