新建list.h
typedef struct _Node
{
struct _Node* prior;
struct _Node* next;
void* data;
}NODE;
typedef struct _List
{
NODE* head;
NODE* last;
int length;
}LIST;
LIST* InitList();
int InsertNode(LIST* List,void* data,int size);
int DeleteNode(LIST* List,int index);
void PrintList(LIST* List);
新建list.c
LIST* InitList(){
LIST* List=(LIST*)malloc(sizeof(LIST));
if(List==NULL)
exit(0);
List->head=(NODE*)malloc(sizeof(NODE));
if(List->head==NULL)
exit(0);
memset(List->head,0,sizeof(NODE));
List->last=(NODE*)malloc(sizeof(NODE));
if(List->last==NULL)
exit(0);
memset(List->last,0,sizeof(NODE));
List->head->prior=NULL;
List->head->next=List->last;
List->head->data=NULL;
List->last->prior=List->head;
List->last->next=NULL;
List->head->data=NULL;
List->length=0;
return List;
}
int InsertNode(LIST* List,void* data,int size){
NODE* n;
if(List==NULL || data==NULL || size<=0){
return 0;
}
n=(NODE*) malloc(sizeof(NODE));
if(n==NULL) return 0;
n->data=(void*)malloc(size);
if(n->data==NULL){
free(n);
return 0;
}
memcpy(n->data,data,size);
n->next=List->last;
n->prior=List->last->prior;
List->last->prior->next=n;
List->last->prior=n;
List->length++;
return 1;
}
int DeleteNode(LIST* List,int index){
NODE* p=NULL;
int i=0;
if(List==NULL||index<1 || index>List->length){
return 0;
}
p=List->head->next;
while(i<List->length){
if((i+1)==index)
break;
p=p->next;
i++;
}
p->prior->next=p->next;
p->next->prior=p->prior;
free(p->data);
free(p);
List->length--;
return 1;
}
void PrintList(LIST* List){
NODE* p=NULL;
if(List==NULL){
return;
}
p=List->head->next;
while(p->next!=NULL){
printf("data=%f\n",*((double*)p->data));
p=p->next;
}
}
添加主函数文件main.c
double data[5]={11.1,22.2,33.3,44.4,55.5};
void main(){
LIST *List;
int i=0;
List=InitList();
for(i;i<5;i++){
InsertNode(List,&data[i],sizeof(data[i]));
}
PrintList(List);
DeleteNode(List,5);
PrintList(List);
}
输出结果
data=11.100000
data=22.200000
data=33.300000
data=44.400000
data=55.500000
data=11.100000
data=22.200000
data=33.300000
data=44.400000