NC51 #合并k个已排序的链表#
合并k个已排序的链表
http://www.nowcoder.com/practice/65cfde9e5b9b4cf2b6bafa5f3ef33fa6
思路和合并两个链表一样,多写个for循环而已
class Solution { public: ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) { if(l1 == nullptr) return l2; if(l2 == nullptr) return l1; ListNode* pHead = nullptr; if(l1->val < l2->val) pHead = l1, l1 = l1->next; else pHead = l2, l2 = l2->next; ListNode* pTail = pHead; while(l1 != nullptr && l2 != nullptr) { if(l1->val < l2->val) pTail->next = l1, l1 = l1->next; else pTail->next = l2, l2 = l2->next; pTail = pTail->next; } if(l1 == nullptr) pTail->next = l2; else pTail->next = l1; return pHead; } ListNode *mergeKLists(vector<ListNode *> &lists) { int len = lists.size(); if(len == 0) return nullptr; ListNode * temp = lists[0]; for(int i = 1; i < len; i++) temp = mergeTwoLists(temp, lists[i]); return temp; } };