题解 | #合并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* mergeList(ListNode *A, ListNode *B){ ListNode *res = new ListNode(0); ListNode *p = res; while(A != nullptr && B != nullptr){ if( A->val < B->val ){ p->next = A; A = A->next; }else{ p->next = B; B = B->next; } p = p->next; } if (A != nullptr){ p->next = A; } if (B != nullptr) { p->next = B; } return res->next; } ListNode* mergeKLists(vector<ListNode*>& lists) { // write code here int lists_num = lists.size(); if(lists_num == 0){ return nullptr; } vector<vector<int>> vals_array; ListNode *A = lists[0]; ListNode *res = lists[0]; for (int i = 1; i < lists_num; i++) { res = mergeList(A,lists[i]); A = res; } return res; } };