线性表的简单编程
#include <stdio.h>
#include <stdlib.h>
typedef int datatype ;
struct sqlist{
datatype *data ;
int length ;
int current;
};
/*初始化线性表*/
void initList( struct sqlist * l, int size)
{
if(size <=0){
printf(" sqlist length can't <= 0\n");
exit(1);
}
l->length = size;
l->current = 0;
l->data = malloc(sizeof(datatype)*size);
if(!l->data) //判断空间是否分配成功
{
printf(" data malloc failure \n");
exit(1);
}
}
/*清除线性表*/
void clearList(struct sqlist *l){
if(l->data){
free(l->data);
l->current = 0 ;
l->length = 0 ;
}
}
/*向线性表插入数据*/
int inserList(struct sqlist *l,datatype x,int n){
if(!l->data){
printf(" error: List is null \n");
return 1 ;
}
if(l->length < n ){
printf("error: n beyond List' capacity \n");
return 1;
}
*(l->data+n-1) = x ;
return 0 ;
}
/*删除线性表中的数据*/
int deleList(struct sqlist *l,int n)
{
int i ;
if(n> l->length)
{
printf("error n beyond List capacity\n");
return 1 ;
}
if(n == l->length)
{
l->length --;
return 0 ;
}
else
{
for(i = n ; i < l->length; i++)
{
l->data[i-1] = l->data[i];
}
l->length--;
}
return 0 ;
}
/*打印线性表数据*/
void disList(struct sqlist *l)
{
int i ;
for(i= 0 ; i < l->length;i++)
printf("%i ",l->data[i]);
printf("\n");
}
int main(int argc,char * artv[])
{
struct sqlist * l ;
int i;
l = malloc(sizeof(struct sqlist));
initList(l,7);
for(i = 1 ; i <=l->length ;i++)
inserList(l,i,i);
disList(l);
inserList(l,99,3);
disList(l);
deleList(l,4);
disList(l);
return 0;
}