Вы должны рассмотреть возможность использования функции добавления, чтобы упростить ваш код.Вот пример:
#include <stdio.h>
#include <stdlib.h>
struct List {
struct Node *head;
struct Node *tail;
};
struct Node {
int data;
struct Node *next;
};
void append(struct List *list, struct Node *node) {
struct Node *nodeCopy = malloc(sizeof(struct Node));
nodeCopy->data = node->data;
nodeCopy->next = NULL;
if (list->head == NULL) { // Empty list
list->head = nodeCopy;
list->tail = nodeCopy;
} else {
list->tail->next = nodeCopy;
list->tail = nodeCopy;
}
}
void print(struct List *list) {
for (struct Node *node = list->head; node != NULL; node = node->next) {
printf("%d,", node->data);
}
printf("\n");
}
struct List* SortedMerge(struct Node* a, struct Node* b)
{
struct List *list = malloc(sizeof(struct List));
list->head = NULL;
list->tail = NULL;
while(1)
{
if(a==NULL && b==NULL)
{
break;
}
if(a==NULL && b!=NULL)
{
append(list, b);
b = b->next;
}
else if(b==NULL && a!=NULL)
{
append(list, a);
a = a->next;
}
else if(a->data<=b->data)
{
append(list, a);
a = a->next;
}
else
{
append(list, b);
b = b->next;
}
}
return list;
}
int main() {
struct List listA = { NULL, NULL };
struct List listB = { NULL, NULL };
struct Node node1 = { 1, NULL };
struct Node node2 = { 2, NULL };
struct Node node3 = { 3, NULL };
struct Node node4 = { 4, NULL };
struct Node node5 = { 5, NULL };
append(&listA, &node1);
append(&listA, &node4);
print(&listA);
append(&listB, &node2);
append(&listB, &node3);
append(&listB, &node5);
print(&listB);
struct List *mergedList1 = SortedMerge(listA.head, listB.head);
print(mergedList1);
struct List *mergedList2 = SortedMerge(listB.head, listA.head);
print(mergedList2);
return 0;
}