单向循环链表和单向链表类似,循环链表和链表不同之处是最后一个元素的next指针是否指向头部,循环链表会而单向链表不会
头文件:
#ifndef CYCLE_LINK_LIST
#define CYCLE_LINK_LIST
#include <stdio.h>
#define clist_size(list) ((list)->size)
#define clist_head(list) ((list)->head)
#define clist_data(ele) ((ele)->data)
#define clist_next(ele) ((ele)->next)
typedef struct CycleLinkEle_{
void *data;
struct CycleLinkEle_* next;
}CycleLinkEle,*CycleLinkEleP;
typedef struct CycleLinkList_{
int size;
void (*destroy)(void *data);
CycleLinkEleP head;
} CycleLinkList,*CycleLinkListP;
void clist_init(CycleLinkListP list,void(*destroy)(void *data));
void clist_destroy(CycleLinkListP list);
int clist_ins_next(CycleLinkListP list,CycleLinkEleP element,void *data);
int clist_rm_next(CycleLinkListP list,CycleLinkEleP element,void **data);
#endif //CYCLE_LINK_LIST
源文件:
#include "cycle_link_list.h"
#include <stdlib.h>
#include <string.h>
void clist_init(CycleLinkListP list,void(*destroy)(void *data)){
list->size=0;
list->destroy=destroy;
list->head=NULL;
}
void clist_destroy(CycleLinkListP list){
void *data;
while (clist_size(list)>0) {
if(clist_rm_next(list,list->head,&data)&&list->destroy!=NULL)
list->destroy(data);
}
}
int clist_ins_next(CycleLinkListP list,CycleLinkEleP element,void *data){
CycleLinkEleP ele=malloc(sizeof(CycleLinkEle));
if(!ele)
return 0;
ele->data=data;
int size=clist_size(list);
list->size++;
if(size==0){
ele->next=ele;
list->head=ele;
return 1;
}
if(element!=NULL){
ele->next=element->next;
element->next=ele;
return 1;
}
ele->next=list->head->next;
list->head->next=ele;
list->head=ele;
return 1;
}
int clist_rm_next(CycleLinkListP list,CycleLinkEleP element,void **data){
int size=clist_size(list);
if(size==0)
return 0;
list->size--;
CycleLinkEleP rmNext=element;
if(rmNext==NULL)
rmNext=list->head;
*data=rmNext->next->data;
if(rmNext->next==rmNext)
list->head=NULL;
else{
rmNext->next=rmNext->next->next;
}
free(rmNext->next);
return 1;
}