题目
已知线性表La和Lb中的数据元素按值非递减(非递减就是递增)有序排列,
现要求将La和Lb归并为一个新的线性表Lc,且Lc中的数据元素仍按值非
递减有序排列。
示例输入: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};
代码
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
using namespace std;
int *CreateDynamicArray(int *p, int arrayLength);
int Compare(int La_array[], int Lb_array[], int La_value, int Lb_value);
int main(int argv,char *argc[]){
int *La, *Lb;
int La_Length, Lb_Length, Lc_Length;
bool Perform;
printf("Please input La_Length: ");
scanf("%d", &La_Length);
printf("Please input La_array: ");
La = CreateDynamicArray(La, La_Length);
printf("Please input Lb_Length: ");
scanf("%d", &Lb_Length);
printf("Please input Lb_array: ");
Lb = CreateDynamicArray(Lb, Lb_Length);
Lc_Length = La_Length + Lb_Length;
int Lc[Lc_Length] = {0};
printf("初始化Lc\n");
for(int i = 0; i < Lc_Length; i++){
printf("%d ", Lc[i]);
}
if(!Lc){
printf("Array creation failed!\n");
}
printf("Brfore Merge: \n");
printf("La: ");
for (int i = 0; i < La_Length; i++){
printf("%d ", La[i]);
}
printf("\n");
printf("Lb: ");
for (int i = 0; i < Lb_Length; i++){
printf("%d ", Lb[i]);
}
printf("\n");
printf("After Merge: \n");
int La_Location = 0, Lb_Location = 0, Lc_Location = 0;
while((La_Location <= La_Length) && (Lb_Location <= Lb_Length)){
printf("La_Location:%d La_Length:%d Lb_Location:%d Lb_Length:%d\n", La_Location, La_Length, Lb_Location, Lb_Length);
Perform = Compare(La, Lb, La_Location, Lb_Location);
for(int i = 0; i < Lc_Length; i++){
printf("%d ", Lc[i]);
}
printf("\n");
if (Perform == true){
Lc[Lc_Location] = Lb[Lb_Location];
/*指针下移*/
Lc_Location += 1;
Lb_Location += 1;
}else if (Perform == false){
Lc[Lc_Location] = La[La_Location];
Lc_Location += 1;
La_Location += 1;
}
}
printf("La_Location:%d La_Length:%d", La_Location, La_Length);
if (La_Location > La_Length){
int i,j;
for (i = Lb_Location, j = Lc_Location - 1; j < Lc_Length; i++, j++){
Lc[j] = Lb[i];
}
}else{
int i,j;
for (i = La_Location, j = Lc_Location - 1; j < Lc_Length; i++, j++){
Lc[j] = La[i];
}
}
printf("\nLc: ");
for (int i = 0; i < Lc_Length; i++){
printf("%d ", Lc[i]);
}
free(La);
free(Lb);
free(Lc);
return 0;
}
int *CreateDynamicArray(int *p, int arrayLength){
int c;
p = (int *)malloc(arrayLength*sizeof(int));
for(int i = 0;i < arrayLength; i++)
{
scanf("%d", &c);
p[i] = c;
}
return p;
}
int Compare(int La_array[], int Lb_array[], int La_value, int Lb_value){
bool Judge = true;
if (La_array[La_value] > Lb_array[Lb_value]){
Judge = true;
}else{
Judge = false;
}
return Judge;
}