/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* AddList(ListNode *pHead1,ListNode *pHead2)
{
ListNode *head = new ListNode(0);
head ->next = pHead1;
ListNode *res = head;
while(pHead1 && pHead2)
{
if(pHead1->val <= pHead2->val)
{
head ->next = pHead1;
head = head ->next;
pHead1 = pHead1->next;
}
else
{
head ->next = pHead2;
head = head ->next;
pHead2 = pHead2->next;
}
}
head->next = pHead1?pHead1:pHead2;
return res->next;
}
ListNode *mergeKLists(vector<ListNode *> &lists) {
if(lists.size() == 0)
return nullptr;
for(int i = 1;i<lists.size();++i)
{
lists[0] = AddList(lists[0],lists[i]);
}
return lists[0];
}
};
解题思路:结合上一题合并两个有序链表的方法,逐个将各个链表合并到list[0]



京公网安备 11010502036488号