优化方案
- 定义rear指针始终指向链表的最后一个元素
- 入队时将新元素通过rear插入队尾,且将rear指向元素
- 定义front指针始终指向链表的第一个元素
链式队列的关键状态
- 空队列状态:front = NULL,rear = NULL;
关键操作
- 入队:
- rear->next = node;
- rear = node;
- node->next = NULL;
- 出队:
- front = front->next;
#include <stdio.h>
#include <malloc.h>
#include "LinkQueue.h"
typedef struct tag_LinkQueueNode TLinkQueueNode;
struct tag_LinkQueueNode //队列的节点
{
TLinkQueueNode* next;
void* item;
};
typedef struct tag_LinkQueue //队列头
{
TLinkQueueNode* rear;
TLinkQueueNode* front;
int length;
}TLinkQueue;
LinkQueue* LinkQueue_Create()
{
TLinkQueue* ret = (TLinkQueue*)malloc(sizeof(TLinkQueue));
if(ret != NULL)
{
ret -> rear = NULL;
ret-> front = NULL;
ret->length = 0;
}
return ret;
}
void LinkQueue_Destroy(LinkQueue* queue)
{
LinkQueue_Clear(queue);
free(queue);
}
void LinkQueue_Clear(LinkQueue* queue)
{
while(LinkQueue_Length(queue) >0)
{
LinkQueue_Retrieve(queue);
}
}
int LinkQueue_Append(LinkQueue* queue,void* item)
{
TLinkQueue* sQueue = (TLinkQueue*)queue;
TLinkQueueNode* node = (TLinkQueueNode*)malloc(sizeof(TLinkQueueNode));
int ret = (sQueue != NULL)&&(item != NULL)&&(node != NULL);
if(ret)
{
node->item = item;
if(sQueue->length > 0)
{
sQueue->rear->next = node;
sQueue->rear = node;
node->next = NULL;
}
else
{
sQueue->front = node;
sQueue->rear = node;
node->next = NULL;
}
sQueue->length++;
}
if(!ret)
{
free(node);
}
return ret;
}
void* LinkQueue_Retrieve(LinkQueue* queue)
{
TLinkQueue* sQueue = (TLinkQueue*)queue;
TLinkQueueNode* node = NULL;
void* ret = NULL;
if((sQueue != NULL)&&(sQueue->length >0))
{
node = sQueue->front;
sQueue->front = node->next;
ret = node->item;
free(node);
sQueue->length--;
if(sQueue->length == 0)
{
sQueue->front = NULL;
sQueue->rear = NULL;
}
}
return ret;
}
void* LinkQueue_Header(LinkQueue* queue)
{
TLinkQueue* sQueue = (TLinkQueue*)queue;
void* ret = NULL;
if((sQueue != NULL)&&(sQueue->length > 0))
{
ret = sQueue->front->item;
}
return ret;
}
int LinkQueue_Length(LinkQueue* queue)
{
TLinkQueue* sQueue = (TLinkQueue*)queue;
int ret = -1;
if(sQueue != NULL)
{
ret = sQueue->length;
}
return ret;
}