动态构建顺序表,及顺序表的插入删除算法(C语言)

作为数据结构初学者,发现授课过程中使用的程序,对于书中的算法有所简化(简化了动态分配内存的内容),而其他人的程序也省略了这部分内容,所以就自己敲了一下咯,格式也许不甚规范。
以下程序用VC++6.0调试,确认正确无误。

#include<stdio.h>
#include<stdlib.h>

#define MaxSize 10 
#define begin_length 5   //注意修改
#define listincrement 10
typedef int ElemType;

typedef struct                                              /*顺序表的定义*/
{ 
    ElemType *elem;    //存储空间基址
    int length;       //当前长度
    int listsize;     //当前分配的存储容量单位
}SeqList;

int Init_SeqList(SeqList *L)                            /*初始化一个顺序表*/
{
    L->elem = (ElemType*)malloc(MaxSize*sizeof(ElemType)); 
    if(!L->elem) exit(0);
    L->length = 0;          //空表长度为零
    L->listsize = MaxSize;   //初始化存储容量 
    return 0;
}


int Insert_SeqList(SeqList *L,int i,ElemType x)           /*插入元素*/
{
    ElemType *newbase, *insertptr, *p;  
    if(i<1 || i>L->length+1)  exit(0); //非法插入
    if(L->length >= L->listsize)
    {
        newbase=(ElemType*)realloc(L->elem,(L->listsize+listincrement)*sizeof(ElemType));
        if(!newbase) exit(0);    //存储分配失败
        L->elem = newbase;      //更新内存基址
        L->listsize += listincrement;  //增加存储容量
    }
    insertptr=&(L->elem[i-1]);     
    for(p = &(L->elem[L->length-1]); p >= insertptr; p--)
        *(p+1) = *p;
    *insertptr = x;
    L->length++;
    return 0;
}



int Delete_SeqList(SeqList *L,int i)                      /*删除元素*/
{
  ElemType *deleteptr, *p;
  if(i < 1 || i > L->length) exit(0); //非法删除
  deleteptr=&(L->elem[i-1]);
  p=L->elem+L->length-1;
  for(deleteptr++;deleteptr<=p;deleteptr++) 
      *(deleteptr-1) = *deleteptr;
  L->length--;
  return 0;
}

int Put_SeqList(SeqList *L)               /*打印表*/
{
    ElemType *begin, *end;
    begin = &(L->elem[0]);
    end   = &(L->elem[L->length-1]);
    if(begin == end) exit(0); //判断表是否为空表
    for(;begin < end; begin++)  printf("%d->", *begin);
    printf("%d\n", *end);
    return 0;
}




int main()   //用主函数测试(实现创建一个含有五个元素的顺序表,插入第四个元素,删除第三个元素)
{
    SeqList L;
    ElemType x;
    int i;
    Init_SeqList(&L);
    for(i = 1; i<=begin_length; i++)  //创建最初表
    {
        scanf("%d",&x);
        Insert_SeqList(&L, i, x);
    }

    Put_SeqList(&L);
    Insert_SeqList(&L,4,4);
    Put_SeqList(&L);
    Delete_SeqList(&L,3);
    Put_SeqList(&L);


    return 0;

}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值