C语言顺序表合并算法实现 - 详细代码解析
#include <stdio.h> #include <stdlib.h>
#define MAX_LIST_SIZE 100 #define LISTINCREMENT 10
#define OK 1 #define OVERFLOW 0 typedef int Status;
typedef struct { int *elem; size_t length; size_t listsize; } SqList;
Status InitList(SqList& L, size_t length, size_t listsize) { L.elem = (int *)calloc(listsize, sizeof(int)); L.length = length; L.listsize = listsize; if (!L.elem) { exit(OVERFLOW); } return OK; }
Status MergeList_Sq(const SqList& La, const SqList& Lb, SqList& Lc) { size_t length1 = La.length; size_t length2 = Lb.length; size_t i = 0, j = 0, k = 0;
while (i < length1 && j < length2) {
int ai = La.elem[i];
int bj = Lb.elem[j];
if (ai <= bj) {
Lc.elem[k] = ai;
i++;
} else {
Lc.elem[k] = bj;
j++;
}
k++;
}
while (i < length1) {
Lc.elem[k] = La.elem[i];
i++;
k++;
}
while (j < length2) {
Lc.elem[k] = Lb.elem[j];
j++;
k++;
}
Lc.length = k;
return OK;
}
int main() { SqList La, Lb, Lc; size_t length1, length2;
printf('请输入第一个顺序表的长度:\n');
scanf('%zu', &length1);
if (!InitList(La, length1, MAX_LIST_SIZE)) {
printf('La初始化出错!\n');
return 0;
}
printf('请输入第一个顺序表的序列值:\n');
for (size_t i = 0; i < length1; i++) {
scanf('%d', &La.elem[i]);
}
printf('请输入第二个顺序表的长度:\n');
scanf('%zu', &length2);
if (!InitList(Lb, length2, MAX_LIST_SIZE)) {
printf('Lb初始化出错!\n');
return 0;
}
printf('请输入第二个顺序表的序列值:\n');
for (size_t j = 0; j < length2; j++) {
scanf('%d', &Lb.elem[j]);
}
if (!InitList(Lc, length1 + length2, MAX_LIST_SIZE)) {
printf('Lc初始化出错!\n');
return 0;
}
if (!MergeList_Sq(La, Lb, Lc)) {
printf('顺序表合并出错!\n');
return 0;
}
printf('合并后的顺序表Lc为:');
for (size_t k = 0; k < Lc.length; k++) {
printf('%d ', Lc.elem[k]);
}
printf('\n');
free(La.elem);
free(Lb.elem);
free(Lc.elem);
return 0;
}
原文地址: https://www.cveoy.top/t/topic/lPI 著作权归作者所有。请勿转载和采集!