题解 | #合并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 *mergeTwoList(ListNode *l1,ListNode *l2){ ListNode *l3=new ListNode(0); ListNode *cur=l3; while(l1!=nullptr && l2!=nullptr){ if(l1->val<=l2->val){ cur->next=l1; l1=l1->next; }else{ cur->next=l2; l2=l2->next;
}
cur=cur->next; } if(l1!=nullptr){ cur->next=l1; }else{ cur->next=l2; } return l3->next; }ListNode *mergeKLists(vector<ListNode *> &lists) { int n=lists.size(); if(n==1){ return lists[0]; }else if(n==0){ return nullptr; }else{ ListNode *l1=lists[0]; ListNode *l2=nullptr; for(int i=1;i<n;i++){ l2=lists[i]; l1=mergeTwoList(l1,l2); } return l1; } } };