DS之順序表實現歸併兩個非遞減線性表,ds線性
早在寫線性表的時候就說過這個複雜的操作,今天就來實現歸併。
已知順序表La和Lb中的資料元素按值非遞減有序排列,現要求將La和Lb歸併為一個新的順序表Lc,且Lc中的資料元素扔按值非遞減有序排列。
例如:La=(3,5,8,11)
Lb=(2,6,8,9,11,15,20)
則 Lc=(2,3,4,6,8,8,9,11,11,15,20)
要想實現歸併,用到的順序表的基本操作為:0基本操作前準備,1初始化順序表,6向順序表插入資料元素,以及自己所寫的歸併函數,最後需要在主函數中實現輸入並輸出Lc的所有資料元素。
歸併函數代碼:
<span style="font-size:18px;">//歸併函數void MergeList(SqList La,SqList Lb,SqList &Lc){ ElemType *pa=La.elem; ElemType *pb=Lb.elem;Lc.listsize=Lc.length=La.length+Lb.length; ElemType *pc=Lc.elem=(ElemType*)malloc(Lc.listsize*sizeof(ElemType));//從右向左結合方向 if(!Lc.elem){exit(OVERFLOW);} ElemType *pa_last=La.elem+La.length-1; ElemType *pb_last=Lb.elem+Lb.length-1; while(pa<=pa_last&&pb<=pb_last)//歸併 { if(*pa<=*pb) { *pc++=*pa++; } else { *pc++=*pb++; }}while(pa<=pa_last)//插入La中剩餘的元素{*pc++=*pa++;} while(pb<=pb_last)//插入Lb中剩餘的元素{*pc++=*pb++;}} </span>
完整的實現歸併的代碼為:
<span style="font-size:18px;">#include <iostream>using namespace std;#include <malloc.h>#include <stdlib.h>//0基本操作前準備#define TRUE 1#define FALSE 0#define OK 1#define ERROR 0#define OVERFLOW -2#define LIST_INIT_SIZE 100 #define LISTINCREMENT 10typedef int ElemType;typedef int Status;typedef struct{ElemType *elem;//儲存空間基址int length;//當前長度int listsize;//當前分配的儲存容量}SqList;//定義了一個結構體類型,並命名為Sqlist//1初始化順序表Status InitList(SqList &L){ L.elem=(ElemType *)malloc(LIST_INIT_SIZE*sizeof(ElemType)); if(!L.elem) {exit(OVERFLOW); } L.length=0; L.listsize=LIST_INIT_SIZE; return OK; }//6向順序表插入資料元素Status ListInsert(SqList &L,int i, ElemType e){if(i<1||i>L.length+1){return ERROR;}if (L.length>=L.listsize){ElemType *newbase=(ElemType *)realloc(L.elem,(L.listsize+LISTINCREMENT )*sizeof(ElemType)); if(!newbase){exit(OVERFLOW);} L.elem=newbase; L.listsize+=LISTINCREMENT;} ElemType *q=&(L.elem[i-1]); ElemType *p;for(p=&(L.elem[L.length-1]);p>=q;p--){*(p+1)=*p;} *q=e; ++L.length; return OK;}//歸併函數void MergeList(SqList La,SqList Lb,SqList &Lc){ ElemType *pa=La.elem; ElemType *pb=Lb.elem;Lc.listsize=Lc.length=La.length+Lb.length; ElemType *pc=Lc.elem=(ElemType*)malloc(Lc.listsize*sizeof(ElemType));//從右向左結合方向 if(!Lc.elem){exit(OVERFLOW);} ElemType *pa_last=La.elem+La.length-1; ElemType *pb_last=Lb.elem+Lb.length-1; while(pa<=pa_last&&pb<=pb_last)//歸併 { if(*pa<=*pb) { *pc++=*pa++; } else { *pc++=*pb++; }}while(pa<=pa_last)//插入La中剩餘的元素{*pc++=*pa++;} while(pb<=pb_last)//插入Lb中剩餘的元素{*pc++=*pb++;}} int main(){ SqList La,Lb,Lc;//聲明了La和Lb以及LC; InitList(La); InitList(Lb); cout<<"請輸入La中資料的個數:"; int na; ElemType e; cin>>na; for(int i=1;i<=na;i++) { cin>>e; ListInsert(La,i,e); } cout<<"請輸入Lb中資料的個數:"; int nb; cin>>nb; for(i=1;i<=nb;i++) { cin>>e; ListInsert(Lb,i,e); } MergeList(La,Lb,Lc); for(i=0;i<na+nb;i++) { cout<<Lc.elem[i]<<","; } cout<<endl; return 0;}</span>
輸入的資料為:La=(2,5,6)
Lb=(3,5,7,9,11)
輸出的結果為: