在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);
這些方法可以根據實際需求選擇使用,每種方法都有其適用的場景和優缺點。