题解 | #合并k个已排序的链表#
合并k个已排序的链表
http://www.nowcoder.com/practice/65cfde9e5b9b4cf2b6bafa5f3ef33fa6
思路:合并两个链表,遍历给定的数组。
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
ListNode* ans= new ListNode(-1);
ListNode* head = ans;
while (l1 != NULL && l2 != NULL) {
if (l1->val < l2->val) {
head->next = l1;
l1 = l1->next;
}
else {
head->next = l2;
l2 = l2->next;
}
head = head->next;
}
head->next = l1 == NULL ? l2 : l1;
return ans->next;
}
ListNode* mergeKLists(vector<ListNode*>& lists) {
ListNode* ans = NULL;
for (int i = 0; i < lists.size(); i++) {
ans=mergeTwoLists(ans, lists[i]);
}
return ans;
}
};