视频讲解在这:👇
p18 第7题 c语言代码实现王道数据结构课后代码题_哔哩哔哩_bilibili
本题代码如下
int merge(struct sqlist* A, struct sqlist* B, struct sqlist* C)
{
if (A->length + B->length > C->length)//大于顺序表的最大长度
return false;
int i = 0;
int j = 0;
int k = 0;
while (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 true;
}
完整测试代码
#include<stdio.h>
#define true 1
#define false 0
#define Max 10
struct sqlist
{
int data[Max];
int length;
};
int merge(struct sqlist* A, struct sqlist* B, struct sqlist* C)
{
if (A->length + B->length > C->length)//大于顺序表的最大长度
return false;
int i = 0;
int j = 0;
int k = 0;
while (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 true;
}
int main()
{
struct sqlist A = { 1,3,5,7 };
struct sqlist B = { 2,4,6 };
A.length = 4;
B.length = 3;
struct sqlist C;
C.length = 7;
printf("A顺序表为:");
for (int i = 0; i < A.length; i++)
printf("%d", A.data[i]);
printf("\nB顺序表为");
for (int j = 0; j < B.length; j++)
printf("%d", B.data[j]);
if (!merge(&A, &B, &C))
{
printf("错误");
}
else
{
printf("\n合并后的顺序表C为:");
for (int i = 0; i < C.length; i++)
printf("%d", C.data[i]);
}
return 0;
}