题解 | #合并k个已排序的链表#
合并k个已排序的链表
https://www.nowcoder.com/practice/65cfde9e5b9b4cf2b6bafa5f3ef33fa6
/** * struct ListNode { * int val; * struct ListNode *next; * }; */ struct ListNode* merge(struct ListNode* head1, struct ListNode* head2); /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param lists ListNode类一维数组 * @param listsLen int lists数组长度 * @return ListNode类 */ struct ListNode* mergeKLists(struct ListNode** lists, int listsLen ) { // write code here struct ListNode* nHead = lists[0]; for(int i = 1; i < listsLen; i++){ nHead = merge(nHead, lists[i]); } return nHead; } struct ListNode* merge(struct ListNode* head1, struct ListNode* head2) { // write code here if(head1 == NULL){ return head2; } if(head2 == NULL){ return head1; } if(head1->val > head2->val){ head2->next = merge(head1,head2->next); return head2; }else{ head1->next = merge(head1->next,head2); return head1; } }