题解 | #合并k个已排序的链表#
合并k个已排序的链表
https://www.nowcoder.com/practice/65cfde9e5b9b4cf2b6bafa5f3ef33fa6
/** * struct ListNode { * int val; * struct ListNode *next; * ListNode(int x) : val(x), next(nullptr) {} * }; */ class Solution { public: /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param lists ListNode类vector * @return ListNode类 */ ListNode* mergeTwoLists(ListNode* head1,ListNode* head2) { if(head1 == nullptr || head2 == nullptr) return head1 == nullptr ? head2 : head1; ListNode* head = head1->val <= head2->val ? head1 : head2; ListNode* cur1 = head->next; ListNode* cur2 = head == head1 ? head2 : head1; ListNode* pre = head; while(cur1 && cur2) { if(cur1->val <= cur2->val) { pre->next = cur1; cur1=cur1->next; }else{ pre->next = cur2; cur2=cur2->next; } pre = pre->next; } pre->next = cur1 ? cur1 : cur2; return head; } ListNode* mergeKLists(vector<ListNode*>& lists) { if(lists.size() == 0) return {}; if(lists.size() == 1) return lists[0]; // write code here ListNode* head1 = lists[0]; ListNode* head2 = lists[1]; ListNode* head = mergeTwoLists(head1,head2); for(int i=2;i<lists.size();i++) { head = mergeTwoLists(head,lists[i]); } return head; } }; // [{1,2},{1,4,5},{6}] // {1,1,2,4,5,6} // {1,2},{1,4,5} // {1,1,2,4,5} {6} // {1,1,2,4,5,6}