c语言队列实现(不强制数据类型,包含三种实现)
立即下载
资源介绍:
c语言队列实现(不强制数据类型,包含三种实现)
#include
#include
void helloQueueLink(){
printf("%s\n","hello LinkedQueue!");
}
//队列节点
typedef struct QueueNode{
void* data;
struct QueueNode *next;//后继元素
struct QueueNode *front;//前驱元素
}QueueNode;
//队列对象(链式队列)
typedef struct LinkedQueue{
QueueNode *head; //队列头
QueueNode *rear; //队列尾
int size; //最大容量
}LinkedQueue;
//创建队列,队列长度固定且默认,由size决定
LinkedQueue* createQueueLink(){
LinkedQueue* queue = (LinkedQueue*) malloc(sizeof(LinkedQueue));
queue->size = 0;
queue->head = (QueueNode*)malloc(sizeof(QueueNode));
queue->rear = queue->head;
queue->rear->next = NULL;
queue->rear->front = NULL;
return queue;
}
//队列是否已空
int linkedQueueIsEmpty(LinkedQueue *queue){
if(queue->size == 0){
return 1;
}else{
return 0;
}
}
//链式队列不会满
//入队列
void linkedQueueEnQueue(void* val,LinkedQueue *queue){
QueueNode *node = (QueueNode*)malloc(sizeof(QueueNode));
node->data = val;
node->front = queue->rear; //新元素的前驱为 队列的尾元素
node->next = NULL; //新元素的后继为 NULL
queue->rear->next = node; //尾元素的后继为 新元素
queue->rear = node; //移动队尾指针到新元素
queue->size = queue->size+1;
}
//出队列
void* linkedQueueDeQueue(LinkedQueue *queue){
if(linkedQueueIsEmpty(queue) == 1){
printf("出队列失败,队列已空!\n");
return NULL;
}else{
QueueNode *node = queue->head;
queue->head = queue->head->next;
queue->size = queue->size - 1;
void* val = queue->head->data;
free(node);
return val;
}
}
//获取队首元素
void* linkedQueueGetQueue(LinkedQueue *queue){
if(linkedQueueIsEmpty(queue) == 1){
printf("出队列失败,队列已空!\n");
return NULL;
}else{
QueueNode *node = queue->head->next;
void* val = node->data;
return val;
}
}
void linkedQueueDestroy(LinkedQueue *queue){
QueueNode *node = queue->head;
while(node != NULL){
free(node);
node = node->next;
}
free(queue);
}