代码实现:
/** * Definition for singly-linked list. * struct ListNode { * int val; * struct ListNode *next; * }; */ struct ListNode* merge(struct ListNode *l1, struct ListNode *l2) { if (l1 == NULL) { return l2; } if (l2 == NULL) { return l1; } struct ListNode *head = malloc(sizeof(*head)); // 设置虚拟头结点 struct ListNode *tail = head; while (l1 && l2) { if (l1->val < l2->val) { tail->next = l1; l1 = l1->next; } else { tail->next = l2; l2 = l2->next; } tail = tail->next; tail->next = NULL; } if (l1) { tail->next = l1; } if (l2) { tail->next = l2; } struct ListNode *result = head->next; head->next = NULL; free(head); return result; } struct ListNode* mergeKLists(struct ListNode **lists, int listsSize){ if (lists == NULL || listsSize == 0) { return NULL; } struct ListNode *h = NULL; for (int i = 0; i < listsSize; i++) { h = merge(lists[i], h); } return h; }