在上一篇博客中,我们实现了顺序队列的编写。现在我们来实现链式队列的编写。
linkqueue.h:
#pragma once
#include
#include
#include
typedef char LinkQueueType;
typedef struct LinkNode{
LinkQueueType data;
struct LinkNode* next;
}LinkNode;
typedef struct LinkQueue{
LinkNode* head;
LinkNode* tail;
}LinkQueue;
void LinkQueueInit(LinkNode** q);
void LinkQueuePrint(LinkNode* q,const char* msg);
LinkNode* CreateNode(LinkQueueType value);
void LinkQueueDestroy(LinkNode** q);
void LinkQueuePush(LinkNode** q,LinkQueueType value);
void LinkQueuePop(LinkNode** q);
int LinkQueueFront(LinkNode* q,LinkQueueType* value);
linkqueue.c:
#include "linkqueue.h"
void LinkQueueInit(LinkNode** q){
if(q == NULL){
return;
}
*q = NULL;
}
void LinkQueueDestroy(LinkNode** q){
if(q == NULL){
return;
}
LinkNode* cur = *q;
for(;cur != NULL;cur = cur->next){
free(cur);
}
*q = NULL;
}
LinkNode* CreateNode(LinkQueueType value){
LinkNode* new_node = (LinkNode*)malloc(sizeof(LinkNode));
new_node->data = value;
new_node->next = NULL;
return new_node;
}
void LinkQueuePrint(LinkNode* q,const char* msg){
printf("[%s]\n",msg);
LinkNode* cur = q;
for(;cur != NULL;cur = cur->next){
printf("[%c] ",cur->data);
}
printf("\n");
}
void LinkQueuePush(LinkNode** q,LinkQueueType value){
if(q == NULL){
return;
}
LinkNode* new_node = CreateNode(value);
new_node->next = *q;
*q = new_node;
}
void LinkQueuePop(LinkNode** q){
if(q == NULL){
return;
}
if(*q == NULL){
return;
}
LinkNode* to_delete = *q;
*q = (*q)->next;
free(to_delete);
}
int LinkQueueFront(LinkNode* q,LinkQueueType* value){
if(q == NULL){
return 0;
}
*value = q->data;
return 1;
}
test.c:
#include "linkqueue.h"
#define PRINT_HEAD printf("\n============%s============\n",__FUNCTION__)
void test(){
PRINT_HEAD;
LinkNode* q;
LinkQueueInit(&q);
LinkQueuePrint(q,"队列的初始化");
LinkQueuePush(&q,'a');
LinkQueuePush(&q,'b');
LinkQueuePush(&q,'c');
LinkQueuePush(&q,'d');
LinkQueuePrint(q,"入队列四个元素");
LinkQueueType value;
int ret = LinkQueueFront(q,&value);
printf("ret except 1,actual %d\n",ret);
printf("front except d,actual %c\n",value);
LinkQueuePop(&q);
LinkQueuePrint(q,"出队列一个元素");
ret = LinkQueueFront(q,&value);
printf("ret except 1,actual %d\n",ret);
printf("front except c,actual %c\n",value);
LinkQueuePop(&q);
LinkQueuePrint(q,"出队列两个元素");
ret = LinkQueueFront(q,&value);
printf("ret except 1,actual %d\n",ret);
printf("front except b,actual %c\n",value);
LinkQueuePop(&q);
LinkQueuePrint(q,"出队列三个元素");
ret = LinkQueueFront(q,&value);
printf("ret except 1,actual %d\n",ret);
printf("front except a,actual %c\n",value);
LinkQueuePop(&q);
LinkQueuePrint(q,"出队列四个元素");
ret = LinkQueueFront(q,&value);
printf("ret except 0,actual %d\n",ret);
LinkQueuePop(&q);
LinkQueuePrint(q,"尝试对空队列操作");
LinkQueuePush(&q,'a');
LinkQueuePush(&q,'b');
LinkQueuePush(&q,'c');
LinkQueuePush(&q,'d');
LinkQueuePrint(q,"入队列四个元素");
LinkQueueDestroy(&q);
LinkQueuePrint(q,"销毁队列");
}
int main(){
test();
}
结果演示: