一维数据构建线性表

线性表的简单编程

#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;
}


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值