将两个有序顺序表合并成一个新的有序表,并有函数返回有序顺序表
#include <iostream>
using namespace std;
typedef int ElemType;
#define Maxsize 100
#define OK 1
#define ERROR 0
typedef struct SqList
{
ElemType data[Maxsize];
int length;
}SqList;
void Init_SqList(SqList& L)
{
L.length = 0;
}
SqList merge(SqList A, SqList B, SqList& C)
{
if (C.length < A.length + B.length)
{
cout << "新创建线性表空间不足!!!";
exit(0);
}
int i = 0, j = 0;
int k = 0;
for (; i < A.length&&j < B.length;)
{
if (A.data[i] <= B.data[j])
C.data[k++] = A.data[i++];
else
C.data[k++] = B.data[j++];
}
while (i < A.length)
{
C.data[k++] = A.data[i++];
}
while (j < B.length)
{
C.data[k++] = B.data[j++];
}
C.length = k;
return C;
}
//L1 1 2 4 7 8
//L2 3 4 6
//将两个有序顺序表合并成一个新的有序表,并有函数返回有序顺序表
int main(void)
{
cout << "---------第一个顺序表---------" << endl;
SqList L1;
Init_SqList(L1);
L1.data[0] = 1;
L1.data[1] = 2;
L1.data[2] = 4;
L1.data[3] = 7;
L1.data[4] = 8;
L1.length = 5;
for (int i = 0; i < L1.length; i++)
cout << L1.data[i] << " ";
cout << endl;
cout << "---------第二个顺序表---------" << endl;
SqList L2;
Init_SqList(L2);
L2.data[0] = 3;
L2.data[1] = 4;
L2.data[2] = 6;
L2.length = 3;
for (int i = 0; i < L2.length; i++)
cout << L2.data[i] << " ";
cout << endl;
cout << "---------第三个顺序表---------" << endl;
SqList L3;
Init_SqList(L3);
L3.length = 20;
merge(L1, L2, L3);
for (int i = 0; i < L3.length; i++)
cout << L3.data[i] << " ";
cout << endl;
return 0;
}