您的位置:首页 > 编程语言 > C语言/C++

用c语言实现队列(FIFO)

2016-08-05 15:17 417 查看
队列是一种先进先出的数据结构,它的存储表示方式有两种:顺序存储和链式存储

顺序存储由于要考虑假溢出的情况,所以采用循环队列形式:



c语言实现:

#define QUEUESIZE 100 //定义队列的大小
typedef int DataType; //定义队列元素类型

typedef struct
{
DataType data[QUEUESIZE];
int front; //指向队头的索引,这个所指的空间不存放元素
int tail; //指向队尾的索引,存放最后一个元素
}CircleQueue;

bool InitCircleQueue(CircleQueue *pCQ)
{
pCQ = (CircleQueue *)malloc(sizeof(CircleQueue));
if (pCQ == NULL)
return false;
else
{
pCQ->front = 0;
pCQ->tail = 0;
return true;
}
}

bool IsQueueEmpty(CircleQueue *pCQ)
{
if (pCQ->front == pCQ->tail)
return true;
else
return false;
}

bool IsQueueFull(CircleQueue *pCQ)
{
if ((pCQ->tail + 1) % QUEUESIZE == pCQ->front)
return true;
else
return false;
}

bool PushElement(CircleQueue *pCQ, DataType dData)
{
if (IsQueueFull(pCQ))
return false;

pCQ->tail = (pCQ->tail + 1) % QUEUESIZE;
pCQ->data[pCQ->tail] = dData;
return true;
}

bool PopElement(CircleQueue *pCQ, DataType *pData)
{
if (IsQueueEmpty(pCQ))
return false;

pCQ->front = (pCQ->front + 1) % QUEUESIZE;
*pData = pCQ->data[pCQ->front];
return true;
}

bool GetHeadElement(CircleQueue *pCQ, DataType *pData)
{
if (IsQueueEmpty(pCQ))
return false;

*pData = pCQ->data[(pCQ->front + 1) % QUEUESIZE];
return true;
}


队列的链式存储结构简称为链队



c语言实现:

typedef int DataType;

typedef struct qnode
{
DataType data;
struct qnode *next;
}Node, *pNode;

typedef struct
{
pNode front;
pNode rear;
}LinkQueue;

bool InitLinkQueue(LinkQueue *pLQ)
{
pNode p;
p = (pNode)malloc(sizeof(Node));
if (p == NULL)
return false;
else
{
p->next = NULL;
LQ->front = p;
LQ->rear = p;
return true;
}
}

bool IsQueueEmpty(LinkQueue *pLQ)
{
if (pLQ->front == pLQ->rear)
return true;
else
return false;
}

bool PushElement(LinkQueue *pLQ, DataType dData)
{
pNode p;
p = (pNode)malloc(sizeof(Node));
if (p == NULL)
return false;

p->data = dData;
p->next = NULL;
pLQ->rear->next = p;
pLQ->rear = p;
return true;
}

bool PopElement(LinkQueue *pLQ, DataType *pData)
{
pNode p;
if (IsQueueEmpty(pLQ))
return false;

p = pLQ->front->next;
*pData = p->data;
pLQ->front->next = p->next;
if (pLQ->front->next == NULL)
pLQ->rear = pLQ->front;

free(p)
return true;
}

bool GetHeadElement(LinkQueue *pLQ, DataType *pData)
{
if (IsQueueEmpty(pLQ))
return false;

*pData = pLQ->front->next->data;
return true;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  循环队列 c