线性表顺序存储结构

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

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值