實現算法2.2的程序

// algo2-2.cpp 實現算法2.2的程序
#include"c1.h"
typedef int ElemType;
#include"c2-1.h"
#include"bo2-1.cpp"
#include"func2-3.cpp" // 包括equal()、comp()、print()、print2()和print1()函數
void MergeList(SqList La,SqList Lb,SqList &Lc) // 算法2.2
{ // 已知線性表La和Lb中的數據元素按值非遞減排列。
// 歸併La和Lb得到新的線性表Lc,Lc的數據元素也按值非遞減排列
int i=1,j=1,k=0;
int La_len,Lb_len;
ElemType ai,bj;
InitList(Lc); // 創建空表Lc
La_len=ListLength(La);
Lb_len=ListLength(Lb);
while(i<=La_len&&j<=Lb_len) // 表La和表Lb均非空
{
GetElem(La,i,ai);
GetElem(Lb,j,bj);
if(ai<=bj)
{
ListInsert(Lc,++k,ai);
++i;
}
else
{
ListInsert(Lc,++k,bj);
++j;
}
} // 以下兩個while循環只會有一個被執行
while(i<=La_len) // 表La非空且表Lb空
{
GetElem(La,i++,ai);
ListInsert(Lc,++k,ai);
}
while(j<=Lb_len) // 表Lb非空且表La空
{
GetElem(Lb,j++,bj);
ListInsert(Lc,++k,bj);
}
}
void main()
{
SqList La,Lb,Lc;
int j,a[4]={3,5,8,11},b[7]={2,6,8,9,11,15,20};
InitList(La); // 創建空表La
for(j=1;j<=4;j++) // 在表La中插入4個元素
ListInsert(La,j,a[j-1]);
printf("La= "); // 輸出表La的內容
ListTraverse(La,print1);
InitList(Lb); // 創建空表Lb
for(j=1;j<=7;j++) // 在表Lb中插入7個元素
ListInsert(Lb,j,b[j-1]);
printf("Lb= "); // 輸出表Lb的內容
ListTraverse(Lb,print1);
MergeList(La,Lb,Lc);
printf("Lc= "); // 輸出表Lc的內容
ListTraverse(Lc,print1);
}

運行的結果如下:

/*
La= 3 5 8 11
Lb= 2 6 8 9 11 15 20
Lc= 2 3 5 6 8 8 9 11 11 15 20
*/


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章