线性表中顺序表的合并

对两个顺序表进行合并,算法的复杂度为O(La.size+Lb.size)。

已知:
顺序线性表La和Lb的元素按值非递减排列
归并La和Lb得到的顺序线性表Lc,Lc的元素也按值非递减排列。

代码定义:

void mergeList(SeqList *La,SeqList *Lb,SeqList *Lc)
{
    Lc->capacity = La->size + Lb->size;
    Lc->base = (ElemType *)malloc(Lc->capacity*sizeof(ElemType));
    assert(Lc->base != NULL);

    int ia=0;
    int ib=0;
    int ic=0;

    while(ia <La->size && ib< Lb->size)
    {
        if(La->base[ia] <= Lb->base[ib]) Lc->base[ic++] = La->base[ia++];
        else Lc->base[ic++] = Lb->base[ib++];
    }

    while(ia <La->size) Lc->base[ic++] = La->base[ia++];   //插入La的剩余元素
    while(ib <Lb->size) Lc->base[ic++] = Lb->base[ib++];   //插入Lb的剩余元素

    Lc->size = ic;
}

调用:

int main()
{
    ElemType item;
    SeqList myList;
    InitSeqList(&myList);
    SeqList youList;
    InitSeqList(&youList);
    SeqList weList;

    push_back(&myList,1);
    push_back(&myList,3);
    push_back(&myList,5);
    push_back(&myList,7);

    push_back(&youList,2);
    push_back(&youList,4);
    push_back(&youList,6);
    push_back(&youList,8);
    push_back(&youList,9);

    mergeList(&myList,&youList,&weList);
    show_list(&weList);

    destroy(&myList);//销毁(程序退出前)
    destroy(&youList);//销毁(程序退出前)
    destroy(&weList);//销毁(程序退出前)
    return 0;

输出:
1 2 3 4 5 6 7 8 9

相关推荐
©️2020 CSDN 皮肤主题: 编程工作室 设计师:CSDN官方博客 返回首页