题解 | #合并k个已排序的链表#
合并k个已排序的链表
https://www.nowcoder.com/practice/65cfde9e5b9b4cf2b6bafa5f3ef33fa6
/** * struct ListNode { * int val; * struct ListNode *next; * }; */ /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param lists ListNode类一维数组 * @param listsLen int lists数组长度 * @return ListNode类 */ struct ListNode *Merge(struct ListNode *pHead1, struct ListNode *pHead2) { if (pHead1 == NULL && pHead2 == NULL) return NULL; struct ListNode *res = (struct ListNode *)malloc(sizeof(struct ListNode) * 1); struct ListNode *dumy = res; struct ListNode *l1 = pHead1; struct ListNode *l2 = pHead2; while (l1 != NULL && l2 != NULL) { struct ListNode *node = (struct ListNode *)malloc(sizeof(struct ListNode) * 1); if (l1->val < l2->val) { node->val = l1->val; l1 = l1->next; } else { node->val = l2->val; l2 = l2->next; } res->next = node; res = res->next; } res->next = l1 == NULL ? l2 : l1; return dumy->next; } /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param lists ListNode类一维数组 输入:[{1,2},{1,4,5},{6}] * @param listsLen int lists数组长度 * @return ListNode类 */ struct ListNode *mergeKLists(struct ListNode **lists, int listsLen) { struct ListNode *result = lists[0]; for (int i = 1; i < listsLen; i++) result = Merge(result, lists[i]); return result; }