1.list.h
# ifndef _LIST_H
# define _LIST_H
# define LIST_INIT_SIZE 10
# define LIST_INCREME 10
typedef struct
{
ElemType * elem;
int length;
int size;
}LIST;
LIST * InitList();
void FreeList(LIST * l);
int InsertList(LIST * l, int i, ElemType * e);
int DeleteList(LIST *l, int i);
# endif
2.stu.h# ifndef _STU_H
# define _STU_H
typedef struct
{
char sno[10];
char name[20];
char sex[3];
int score;
}ElemType;
#endif
3.list.c
# include <stdlib.h>
# include <stdio.h>
# include "stu.h"
# include "list.h"
LIST * InitList()
{
LIST *l = (LIST *)malloc(sizeof(LIST));
if(NULL == l)
exit(-1);
l->elem = (ElemType *)malloc(LIST_INIT_SIZE * sizeof(ElemType));
if(NULL == l->elem)
{
free(l);
exit(-1);
}
l->length = 0;
l->size = LIST_INIT_SIZE;
return l;
}
void FreeList(LIST * l)
{
free(l->elem);
free(l);
}
int InsertList(LIST * l, int i, ElemType * e)
{
ElemType * p = NULL;
ElemType * q = NULL;
ElemType * newElem = NULL;
if(l==NULL || e==NULL)
return 0;
if(i < 1 || i > l->length + 1)
return 0;
if(l->length >= l->size)
{
newElem = realloc(l->elem, (l->size + LIST_INCREME)*sizeof(ElemType));
if(NULL == newElem)
return 0;
l->elem = newElem;
l->size += LIST_INCREME;
}
q = &l->elem[i-1];
for(p=&(l->elem[l->length-1]); p>=q; p--)
*(p+1) = *p;
*q = *e;
++l->length;
return 1;
}
int DeleteList(LIST *l, int i)
{
ElemType * p = NULL;
ElemType * q = NULL;
if(NULL == l)
return 0;
if(i<1 || i>l->length)
return 0;
p = &l->elem[i-1];
q = l->elem[l->length - 1];
for(; p<q; p++)
*p = *(p+1);
--l->length;
return l;
}
4.main.c
# include <stdio.h>
# include "stu.h"
# include "list.h"
ElemType stu[3] =
{
{"S101","张三", "男", 80},
{"S102","小红", "女", 70},
{"S103","王五", "男", 60}
};
void main()
{
int i;
LIST *list = NULL;
list = InitList();
for(i=0; i<3; ++i)
InsertList(list, 1, &stu[i]);
FreeList(list);
}