题解 | #合并k个已排序的链表#
合并k个已排序的链表
https://www.nowcoder.com/practice/65cfde9e5b9b4cf2b6bafa5f3ef33fa6
/** * struct ListNode { * int val; * struct ListNode *next; * }; */ /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param lists ListNode类一维数组 * @param listsLen int lists数组长度 * @return ListNode类 */ #include <stdlib.h> //合并两个链表 struct ListNode*Linklist(struct ListNode*head1,struct ListNode*head2){ if(head1==NULL)return head2; if(head2==NULL)return head1; struct ListNode*H = (struct ListNode*)malloc(sizeof(struct ListNode)); struct ListNode*cur = H; while(head1 && head2){ if(head1->val<=head2->val){ cur->next=head1; head1=head1->next; cur=cur->next; }else { cur->next=head2; head2=head2->next; cur=cur->next; } if(head1==NULL){ cur->next=head2; } if(head2==NULL){ cur->next=head1; } } return H->next; } struct ListNode* mergeKLists(struct ListNode** lists, int listsLen ) { // write code here if(listsLen==0 || listsLen ==1)return *lists; struct ListNode*r = lists[0]; for(int i = 1;i< listsLen;i++){ //从第0个链表和第1个链表合并开始,两两合并成新链表再和下一个链表合并,一直循环到与最后一个链表合并 r = Linklist(r,lists[i]); } return r; }