数据结构笔记——线性表抽象数据类型、顺序表的插入

InitList( *List )             初始化线性表,创建一个空的线性表List
InsertElement( *List,index ,elem )    在线性表List的下标index中插入elem
DeletElement( *List, index, *elem)    删除线性表中第i个元素,并返回删除元素的指针
GetLength( *List )          获得线性表的长度

 

顺序表:

1、 定义线性表的最大存储空间

2、线性表里需要有统一类型的元素

typed int ElementType;相当于给int起了个别名叫ElementType

typedef  struct  {

    int id;

    char *name;

}ElementType;

3、定义顺序表结构

typedef struct  {

    ElementType datas [MAX_SIZE];   元素集合,有限个

    int length;   长度

}

    顺序存储结构

a1  a2  a3.....位置从  1  开始

0    1     2.....下标 ,从 0 开始

 

2019.10.28  顺序表插入算法

向顺序表中的index下标处插入一个元素

1、验证插入后的元素空间是否超过MAX_SIZE

2、index 的值是否合法  [ 0 , MAX_SIZE - 1 ] 

3、插入的index应在lengh之内

4、从第length-1个下标开始,前面一个元素赋值给后面一个元素

 

bool ListInsert(SeqList * &L, int i, ElemType e)
{
    int j;
    if(i < 1 || i > L->length + 1 )
    {
        return false;
    }
    
    i--;
    
    for(j = L->length; j > i; j--)  //把长度 length的值赋给 j,如果 j大于要插入的下标 i,则循环,并把前一个值赋给后一个值
        L->data[j] = L->data[j - 1];
        
    L->data[i] = e;      //进行到下标为 i时,将 e赋给下标为 i的那个数
    L->length++;         //这个数组的长度加一
    
    return true;
}

 另一种写法!

 if ( seqList.length + 1 >= MAX_SIZE )
    {
        printf("数组满,插入失败");
        return;
    }

    if( index < 0 || index > MAX_SIZE )
    {
        printf("只能在规定的范围内插入:( 0 ,%d ),MAX_SIZE-1");
        return;
    }

    if( index > SeqList -> length )
    {
        printf("下标越界");
        return;
    }

    int i;

    for( i = SeqList->length - 1; i >= index; i-- )
    {
        SeqList->datas[i + 1] = SeqList->datas[i];
    }
    //将要插入的值赋给index
    SeqList->datas[index] = element;
    //顺序表的长度加一
    SeqList->length++;

 

 

 

 

posted @ 2019-10-28 10:55  翻斗花园小美Q  阅读(532)  评论(0编辑  收藏  举报