在C语言中,将两个列表合并的方法通常有以下几种:
int list1[] = {1, 2, 3};
int list2[] = {4, 5, 6};
int size1 = sizeof(list1) / sizeof(list1[0]);
int size2 = sizeof(list2) / sizeof(list2[0]);
int merged[size1 + size2];
for (int i = 0; i < size1; i++) {
merged[i] = list1[i];
}
for (int i = 0; i < size2; i++) {
merged[i + size1] = list2[i];
}
struct Node {
int data;
struct Node* next;
};
struct Node* list1 = NULL;
struct Node* list2 = NULL;
// 创建链表1和链表2
struct Node* current = list1;
while (current->next != NULL) {
current = current->next;
}
current->next = list2;
malloc
函数动态分配内存,将两个列表的元素逐个复制到新分配的内存中。int* list1 = (int*)malloc(size1 * sizeof(int));
int* list2 = (int*)malloc(size2 * sizeof(int));
int* merged = (int*)malloc((size1 + size2) * sizeof(int));
// 将元素复制到list1和list2
memcpy(merged, list1, size1 * sizeof(int));
memcpy(merged + size1, list2, size2 * sizeof(int));
free(list1);
free(list2);
这些方法可以根据实际需求选择使用,每种方法都有其适用的场景和优缺点。