1.list.h
# ifndef _LIST_H
# define _LIST_H
typedef struct node
{
void * data;
struct node * pior;
struct node * next;
}NODE;
typedef struct
{
NODE * head;
NODE * last;
int length;
}LIST;
LIST * InitList();
int InsertList(LIST * l, void * data, int size);
int DeleteNode(LIST * l, int index);
void PrintList(LIST * l, int page, int preP, void (*printNode)(void *));
void ClearList(LIST * l);
void DestroyList(LIST ** l);
# endif
2.list.c
# include "list.h"
# include
# include
# include
LIST * InitList()
{
LIST * l = (LIST *)malloc(sizeof(LIST));
if(NULL == l)
exit(-1);
l->head = (NODE *)malloc(sizeof(NODE));
if(NULL == l->head)
exit(-1);
memset(l->head, 0, sizeof(NODE));
l->last = (NODE *)malloc(sizeof(NODE));
if(NULL == l->last)
exit(-1);
memset(l->last, 0, sizeof(NODE));
l->head->next = l->last;
l->last->pior = l->head;
l->length = 0;
return l;
}
int InsertList(LIST * l, void * data, int size)
{
NODE * n = NULL;
if(NULL==l || NULL==data || size<=0)
return 0;
n = (NODE *)malloc(sizeof(NODE));
if(NULL == n)
return 0;
n->data = malloc(sizeof(size));
if(NULL == n->data)
{
free(n);
return 0;
}
memcpy(n->data, data, size);
n->next = l->last;
n->pior = l->last->pior;
l->last->pior->next = n;
l->last->pior = n;
l->length++;
return 1;
}
int DeleteNode(LIST * l, int index)
{
int i;
NODE * p = NULL;
if(NULL == l || index < 1 || index > l->length)
return 0;
p = l->head->next;
while(ilength)
{
i++;
if(i == index)
break;
p = p->next;
}
p->pior->next = p->next;
p->next->pior = p->pior;
free(p->data);
free(p);
l->length--;
return 1;
}
void PrintList(LIST * l, int page, int preP, void (*printNode)(void *))
{
int start, end;
NODE * p = NULL;
if(NULL == l || printNode == NULL)
return;
start = (page-1) *preP + 1;
end = page * preP;
int i = 0;
p = l->head->next;
while(ilength && p->next != NULL)
{
++i;
if(i == start)
break;
p = p->next;
}
for(; i<=end && p->next != NULL; i++)
{
printNode(p->data);
p = p->next;
}
}
void ClearList(LIST * l)
{
if(NULL == l)
return;
while(l->length)
DeleteNode(l, 1);
}
void DestroyList(LIST ** l)
{
LIST *p = *l;
if(NULL == p) return;
ClearList(p);
free(p->head);
free(p->last);
free(p);
*l = NULL;
}
3.main.c
# include
# include
# include
# include "list.h"
int arr[5] = {12, 18, 45, 9, 10};
void PrintData(void * data)
{
int * i = (int *)data;
printf("i = %d\n", *i);
}
void main()
{
int i;
LIST * list = InitList();
for(i=0; i<5; ++i)
InsertList(list, &arr[i], sizeof(arr[i]));
PrintList(list, 1, 3, PrintData);
DestroyList(&list);
if(list == NULL)
printf("list is null\n");
else
printf("list is not null\n");
}