#ifndef _STU_H //stu.h
#define _STU_H
typedef struct
{
char sno[5];
char name[21];
char sex[3];
int score;
}Elemtype;
#endif
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
list.c
#include "stu.h"
#include "list.h"
#include <stdio.h>
#include <stdlib.h>
LIST * InitList()
{
LIST *l=(LIST *)malloc(sizeof(LIST));//not allocate for elements
if(l==NULL)
exit(0);
l->elem=(Elemtype *)malloc(LIST_INIT_SIZE*sizeof(Elemtype));
if(l->elem==NULL)
{
free(l);
exit(0);
}
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)//i代表第几个位置,不是下标
{
Elemtype *p=NULL,*q=NULL,*newElem=NULL;
if(l==NULL || e==NULL)//函数入口参数的检验
return 0;//error
if(i<1 || i>l->length+1)
return 0;
if(l->length>=l->size)//空间已满
{
newElem=(Elemtype *)realloc(l->elem,(l->size+LIST_INCREME)*sizeof(Elemtype));
if(newElem==NULL)
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;//ok
}
int DeleteList(LIST *l,int i)
{
Elemtype *p=NULL,*q=NULL;
if(l == NULL)
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 1;
}
main.c
#include "stu.h"
#include "list.h"
#include <stdio.h>
#include <stdlib.h>
LIST * InitList()
{
LIST *l=(LIST *)malloc(sizeof(LIST));//not allocate for elements
if(l==NULL)
exit(0);
l->elem=(Elemtype *)malloc(LIST_INIT_SIZE*sizeof(Elemtype));
if(l->elem==NULL)
{
free(l);
exit(0);
}
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)//i代表第几个位置,不是下标
{
Elemtype *p=NULL,*q=NULL,*newElem=NULL;
if(l==NULL || e==NULL)//函数入口参数的检验
return 0;//error
if(i<1 || i>l->length+1)
return 0;
if(l->length>=l->size)//空间已满
{
newElem=(Elemtype *)realloc(l->elem,(l->size+LIST_INCREME)*sizeof(Elemtype));
if(newElem==NULL)
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;//ok
}
int DeleteList(LIST *l,int i)
{
Elemtype *p=NULL,*q=NULL;
if(l == NULL)
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 1;
}
VC6调试效果图