**线性列表合并:**
案例分析:
要合并两个线性列表,我们考虑以下情况:
1. 两个列表都是空的:在这种情况下,合并的列表也将是空的。
2. 一个列表是空的:如果其中一个列表是空的,则合并的列表将是非空列表本身。
3. 两个列表都是非空的:在这种情况下,我们同时遍历两个列表,将两个列表中的元素附加到合并的列表中,直到我们到达任一列表的末尾。之后,我们将非空列表中的其余元素附加到合并列表中。
实现:
'''c
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* next;
};
struct Node* mergeLinearLists(struct Node* list1, struct Node* list2) {
if (list1 == NULL)
return list2;
if (list2 == NULL)
return list1;
struct Node* mergedList = NULL;
struct Node* current = NULL;
// Append elements from list1 to merged list
if (list1) {
mergedList = list1;
current = list1;
list1 = list1->next;
}
// Append elements from list2 to merged list
while (list1 && list2) {
current->next = list2;
current = current->next;
list2 = list2->next;
}
// Append remaining elements from list1 or list2
if (list1)
current->next = list1;
else