线性表顺序实现

#include "global.h"
#define LIST_INIT_SIZE 100  //线性表存储空间的初始化分配量
#define LIST_INCREMENT 10   //线性表存储空间的分配增量
struct SqList {   
        ElemType *elem;         //存储空间基址
        int lenth;              //当前表长
        int listsize;           //当前分配的存储空间容量
};

Status InitList_Sq(SqList &L//初始化线性表
{
        L .elem=(ElemType *)malloc(sizeofElemType )*LIST_INIT_SIZE );
        if (!(L .elem))
              exit( OVERFLOW );
        L .lenth=0;
        L .listsize=LIST_INIT_SIZE ;
        return OK ;
}

Status ListInsert_Sq(SqList &Lint i , ElemType e ) //在位置i,插入元素
{
        if (i <1||iL .lenth+1)
               return ERROR ;
        ElemType *newbase;   //保存新地址,可能和原来的地址 不用L.elem是为了提高容错能力
        if (L .lenth>=L.listsize) //当前存储空间已满,增加分配
       {
              newbase=( ElemType *)realloc(L .elem,(L.listsize+ LIST_INCREMENT )*sizeof (ElemType));
               if (!newbase)
                     exit( OVERFLOW );
               L .listsize=L .listsize+LIST_INCREMENT;
               L .elem=newbase;
       } //realloc函数具体说明 见 c与指针P222
       
       
        for (int j=L.lenth-1;j>= i -1;j--) //插入位置及之后的元素右移
       {
               L .elem[j+1]=L .elem[j];
       }
        L .elem[i -1]=e;  //插入e
        L .lenth++;

        return OK ;
}

Status ListDelete_Sq(SqList &Lint i ,ElemType & e )//删除第i个的元素,并用e返回其值
{
        if (i <1 || L.lenth< i )  //i不合法
               return ERROR ;
        e =L .elem[i-1];
        if (i !=L.lenth)        //如果i等于length有可能越界
               for (ElemType *p=&L.elem[ i ];p<=&L .elem[L.lenth-1];p++) //被删除元素之后的元素左移
                     *(p-1)=*p;
        L .lenth--;
        return OK ;
}

Status ListDisplay_Sq(SqList &L)
{
       printf( "memory lenth: %d   datalenth: %d\n" ,L.listsize , L .lenth);
        for (int i=0;i<L.lenth;i++)
       {
              printf( "%3d  " ,L .elem[i]);
               if (i%10==9)
                     putchar( '\n' );
       }
              putchar( '\n' );
        return OK ;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值