参考书籍:《数据结构(第2版)》严蔚敏
- 代码
#include<iostream>
using namespace std;
#define MAXSIZE 100
#define TRUE 1
#define FALSE 0
#define OK 1
#define ERROR 0
#define OVERFLOW -2
typedef int Status;
typedef int ElemType;
//结构体定义
typedef struct
{
ElemType *data;
int length;
} SqList;
//初始化
Status InitList(SqList &L)
{
L.data = new ElemType[MAXSIZE];
if(!L.data) exit(OVERFLOW);
L.length = 0;
return OK;
}
//获得表长
int List_length(SqList L)
{
return L.length;
}
//表L的第i个位置插入元素e
Status ListInsert(SqList &L,int i,ElemType e)
{
if((i<1) || (i>L.length+1)) return ERROR; //位置不合法
if(L.length == MAXSIZE) return ERROR; //表已满
for(int j=L.length-1; j>=i-1; j--)
{
L.data[j+1] = L.data[j];
}
L.data[i-1] = e;
++L.length; //表长加1
return OK;
}
void Merge_List(SqList LA,SqList LB,SqList &LC)
{
LC.length = LA.length + LB.length;
ElemType *pa,*pb,*pc,*pa_last,*pb_last;
pa = LA.data;
pb = LB.data;
pc = LC.data;
pa_last = pa + LA.length-1;
pb_last = pb + LB.length-1;
while((pa<=pa_last)&&(pb<=pb_last))
{
if(*pa<=*pb)
*pc++ = *pa++;
else *pc++ = *pb++;
}
while(pa<=pa_last) *pc++ = *pa++;
while(pb<=pb_last) *pc++ = *pb++;
}
void PrintList(SqList L)
{
int j;
for(j=1;j<=L.length;j++)
cout << L.data[j-1] << " ";
}
int main()
{
SqList LA,LB,LC;
InitList(LA);InitList(LB);InitList(LC);
ListInsert(LA,1,3);
ListInsert(LA,2,5);
ListInsert(LA,3,8);
ListInsert(LA,4,11);
ListInsert(LB,1,2);
ListInsert(LB,2,6);
ListInsert(LB,3,8);
ListInsert(LB,4,9);
ListInsert(LB,5,11);
ListInsert(LB,6,15);
ListInsert(LB,7,20);
cout << "当前线性表LA的长度为:" << List_length(LA) <<endl;
cout << "当前表LA的元素为:";
PrintList(LA);
cout << endl;
cout << "当前线性表LB的长度为:" << List_length(LB) <<endl;
cout << "当前表LB的元素为:";
PrintList(LB);
cout << endl;
Merge_List(LA,LB,LC);
int a=List_length(LC);
cout << "表LC的长度:" << a <<endl;
cout << "表LC的元素为:";
PrintList(LC);
}
- 运行结果