线性表算法2.2:顺序表的合并

本文介绍了两种线性表合并的方法:一种是破坏原有链表的实现,通过比较元素大小,将元素依次插入新的列表中;另一种是非破坏性的合并,利用标记定位元素位置,保留原列表结构。详细阐述了每种方法的步骤和代码实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

//破坏原有的链表实现合并:

void MergeList(List La,List Lb,List &Lc)

{

       ListClear(Lc);

       ElemType ea,eb;

       while(!ListEmpty(La)&&!ListEmpty(Lb)){

              GetElem(La,1,ea);

              GetElem(Lb,1,eb);

              if(ea<eb){

                     ListInsert(Lc,ListLength(Lc)+1,ea);

                     DeleteList(La,2);

              }

              else{

                     ListInsert(Lc,ListLength(Lc)+1,eb);

                     DeleteList(Lb,2);

              }           

       }

       if(ListEmpty(La)){

              while(!ListEmpty(Lb)){

                     GetElem(Lb,1,eb);

                     ListInsert(Lc,ListLength(Lc)+1,eb);

                     DeleteList(Lb,2);

              }

       }

       else{             

              while(!ListEmpty(La)){              

                     GetElem(Lb,1,ea);               

                     ListInsert(Lc,ListLength(Lc)+1,ea);                   

                     DeleteList(La,2);          

              }    

       }

}

//非破坏性的合并:(使用标记来定位线性表元素的位置)

void MergeList(List La,List Lb,List &Lc){  

       int indexa=indexb=1;    

       int k=0;   ElemType ea,eb;    

       int len_La=ListLength(La);   

       int len_Lb=ListLength(Lb);  

       InitList(Lc);   

       while((indexa<=len_La)&&(indexb<=len_Lb)){//线性表逻辑非空         

              GetElem(La,indexa);           

              GetElem(Lb,indexb);           

              if(ea<=eb){                 

                     ListInsert(Lc,++k,ea);                 

                     ++indexa;                    

              }           

              else{                    

                     ListInsert(Lc,++k,eb);                 

                     ++indexb;             

              }    

       }    

       //剩下单个线性表:使用循环顺序插入    

       while(indexb<=len_Lb){//线性表b逻辑非空           

              GetElem(Lb,indexb,eb);              

              ListInsert(Lc,++k,eb);   

       }    

       while(indexa<=len_La){//线性表a逻辑非空            

              GetElem(La,indexa,ea);              

              ListInsert(Lc,++k,ea);   

       }

}

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值