1.list.h
# ifndef _LIST_H
# define _LIST_H
typedef struct _node
{
void * data;
struct _node * next;
}NODE;
typedef struct
{
NODE * head;
NODE * last;
int length;
}LIST;
LIST * InitList();
int InsertList(LIST *l, void * data, int size);
NODE * FindNodeByKey(LIST *l, void * key, int (*compare)(void *, void *));
int DeleteListByKey(LIST * l, void * key, int (*compare)(void *, void *));
# endif
2.list.c
# include "list.h"
# include <stdio.h>
# include <stdlib.h>
# include <string.h>
LIST * InitList()
{
LIST * l = (LIST *)malloc(sizeof(LIST));
if(NULL == l)
exit(-1);
memset(l, 0, sizeof(LIST));
return l;
}
int InsertList(LIST *l, void * data, int size)
{
NODE * n = NULL;
if(NULL == l || data == NULL)
return 0;
n = (NODE *)malloc(sizeof(NODE));
if(n == NULL)
return 0;
// n->data = data;有bug存在
n->data = malloc(size);
if(NULL == n->data)
{
free(n);
return 0;
}
memcpy(n->data, data, size);
n->next = NULL;
if(NULL == l->head)
l->head = n;
else
l->last->next = n;
l->last = n;
l->length++;
return 1;
}
NODE * FindNodeByKey(LIST *l, void * key, int (*compare)(void *, void *))
{
NODE * p = NULL;
if(l==NULL || key==NULL || compare==NULL)
return 0;
p = l->head;
while(p)
{
if(compare(p->data, key) == 1)
return p;
p = p->next;
}
return NULL;
}
NODE * FindNodePre(LIST *l, void * key, int (*compare)(void *, void *), NODE ** pre)
{
NODE * p = NULL;
if(l==NULL || key==NULL || compare==NULL || pre == NULL)
return 0;
p = l->head;
*pre = NULL;
while(p)
{
if(compare(p->data, key) == 1)
return p;
* pre = p;
p = p->next;
}
return NULL;
}
int DeleteListByKey(LIST * l, void * key, int (*compare)(void *, void *))
{
NODE * p = NULL;
NODE * q = NULL;
p = FindNodePre(l, key, compare, &q);
if(NULL == p)
return 0;
if(NULL == q)
l->head = p->next;
else
q->next = p->next;
if(p == l->last)
l->last = q;
free(p->data);
free(p);
l->length--;
return 1;
}
3.main.c
# include "list.h"
# include <string.h>
# include <stdio.h>
struct STU
{
char sno[5];
char name[20];
int age;
int score;
}s[3] = {
{"S01", "zhang san", 15, 90},
{"S02", "li si", 13, 70},
{"S03", "wang wu", 12, 50}
};
int CompareByName(void * info, void * key)
{
struct STU * stu = (struct STU *) info;
char * name = (char *)key;
return strcmp(stu->name, name) == 0 ? 1 : 0;
}
int CompareBySno(void * info, void * key)
{
struct STU * stu = (struct STU *) info;
char * sno = (char *)key;
return strcmp(stu->sno, sno) == 0 ? 1 : 0;
}
void main()
{
int i;
NODE * res = NULL;
char name[] = "Li bai";
char sno[] = "S02";
LIST * list = InitList();
for(i=0; i<3; ++i)
{
InsertList(list, &s[i], sizeof(s[i]));
}
res = FindNodeByKey(list, name, CompareByName);
if(res == NULL)
printf("The value is not the list!\n");
else
printf("The value is found!\n");
if(DeleteListByKey(list, sno, CompareBySno))
printf("Delete success\n");
else
printf("Delete fail\n");
}