/*
一、关于链式队列的约定(目的是在C语言中描述方便)
1.定义:
(1)队列是一种先进先出的线性表;
(2)它只允许在表的一端进行入队,在另一端进行出队操作。在队列中,允许插入的一端
叫队尾,允许删除的一端较队头,即入队只能从队尾入,出队只能从队头出;
(3)运算受限的非循环单链表,头尾结点都有,链表中的插入删除操作在这里只能在队头
队尾进行。
(4)对头指针指向有效数据,并且可移动;队尾指针指向的结点不存有效数据,指针域
指向空NULL,永不移动。
2.创建链式队列时:需定义两个结构,一个用于描述结点(此结构跟链表结点对应的结构类
似),一个用于描述式哪个队列(此结构包括队头和队尾指针);与创建一个空链表类似。
队头指针和队尾指针都指向不存放有效数据的头结点,此头结点的指针域指向NULL。
3.入队,出队,编历,判断是否为空(链式队列不存在满问题),清空队列等操作。
4.在C语言中不能使用动态分配的一维数组来实现循环队列。如果用户程序中有循环队列,则必须为它设定一个最大队列长度,若用户无法预估所用队列最大长度,则宜采用链队列。
*/
#include "LinkedQueue.h"
void linkedQueueCreat(struct linkedQueue *qQ)
{
qQ->pFront = (struct linkedQueueNode *)malloc(sizeof(struct linkedQueueNode));
if( NULL == qQ->pFront )
{
printf("linkedQueueCreat(): malloc failed!\n");
exit(-1);
}
qQ->pRear = qQ->pFront;
qQ->pRear->pNext = NULL;
return;
}
//入队,链式队列不存在满的情况
void enLinkedQueue(struct linkedQueue *qQ,int val)
{
struct linkedQueueNode * pNew = (struct linkedQueueNode *)malloc(sizeof(struct linkedQueueNode));
if( NULL == pNew )
{
printf("enLinkedQueue(): malloc failed!\n");
exit(-1);
}
pNew->data = val;
qQ->pRear->pNext = pNew;//从队尾入,把pNew指向的结点挂到队列尾部
pNew->pNext = NULL;
qQ->pRear = pNew;//尾指针上移
return;
}
int linkedQueueEmpty(struct linkedQueue *qQ)
{
if( qQ->pFront == qQ->pRear)
return 1;
else
return 0;
}
//出队,要判断是否为空
void outLinkedQueue(struct linkedQueue *qQ,int *pVal)
{
if( linkedQueueEmpty(qQ) )
{
printf("linkedQueue is Empty!\n");
return;
}
struct linkedQueueNode * pTemp = qQ->pFront->pNext;//从队头出队,pHead指向的结点不出队,这个结点没有实际意义。队首结点是pHead->pNext指向的结点。
*pVal = pTemp->data;
qQ->pFront->pNext = pTemp->pNext;
free(pTemp);
if( NULL == qQ->pFront->pNext )
{
qQ->pFront = qQ->pRear;//当队列最后一个元素被删除后,队列尾指针也丢失了,因此需对队尾指针重新赋值,即指向头结点。
}
return;
}
//遍历队列,并返回队列的长度
void traverseLinkedQueue(struct linkedQueue *qQ,int *linkedQueueLen)
{
int i=0;
struct linkedQueueNode * pTemp = qQ->pFront->pNext;
while( pTemp != NULL )
{
i++;
printf("data-%d is %d\n",i,pTemp->data);
pTemp = pTemp->pNext;
}
*linkedQueueLen = i;
return;
}
//清空队列,使其变为空队列,框架还在
int clearLinkedQueue(struct linkedQueue *qQ)
{
int pVal=0;
while( !(linkedQueueEmpty(qQ)) )
outLinkedQueue(qQ,&pVal);
return;
}
相关头文件:
#ifndef LINKEDQUEUE_H
#define LINKEDQUEUE_H
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
struct linkedQueueNode
{
int data;
struct linkedQueueNode *pNext;
};
struct linkedQueue
{
struct linkedQueueNode * pFront;
struct linkedQueueNode * pRear;
};
void linkedQueueCreat(struct linkedQueue *qQ);
void enLinkedQueue(struct linkedQueue *qQ,int val);
int linkedQueueEmpty(struct linkedQueue *qQ);
void outLinkedQueue(struct linkedQueue *qQ,int *pVal);
void traverseLinkedQueue(struct linkedQueue *qQ,int *linkedQueueLen);
int clearLinkedQueue(struct linkedQueue *qQ);
#endif