本文主要是介绍王道p18 07.将两个有序顺序表合并为一个新的有序顺序表,并由函数返回结果顺序表。(c语言代码实现),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
视频讲解在这:👇
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++];elseC->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++];elseC->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;
}
这篇关于王道p18 07.将两个有序顺序表合并为一个新的有序顺序表,并由函数返回结果顺序表。(c语言代码实现)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!