C语言数据结构之数据表——向顺序表插入元素

向静态生成表中插入元素:

向顺序表Sqlist中第i个位置插入元素item, 该顺序表原长度为n

void InsertElem(ElemType Sqlist[], int &n, int i, ElemType item){
    int t;
    if(n==MaxSize || i<1 || i>n+1)
        exit(0);    //非法插入
    for(t=n-1; t>=i-1; t--)
        Sqlist[t+1]=Sqlist[t];      //将i-1以后的元素顺序后移一个元素的位置
    Sqlist[i-1]=item;           //在第i个位置插入元素item
    n=n+1;                      //表长加1
}

向顺序表L中第i个位置上插入元素item,并将顺序表长度加1

void InsertElem(Sqlist *L, int i, ElemType item){
    ElemType *base, * insertPtr, *p;
    if(i<1||i>L->length+1) exit(0);     //非法插入
    if(L->length>=L->listsize)
    {
        base=(ElemType*)realloc(L->elem, (L->listsize+10)*sizeof(ElemType));
        //重新追加空间
        L->elem=base;       //更新内存基地址
    L->listsize=L->listsize+100;    //存储空间增大100单元
    }
    insertPtr=&(L->elem[i-1]);      //insert为插入位置
    for(p=&(L->elem[L->length-1]); p>= insertPtr; p--)
        *(p+1)=*p;
    *insertPtr=item;        //在第i个位置上插入元素item
    L->length++;        //表长加1
}
posted @ 2021-11-09 20:15  zonkidd  阅读(1011)  评论(0编辑  收藏  举报