利用之前做过的合并两个链表的函数,进行逐一合并。但是第二种方法也就是新建链表的方法,由于需要 不断开辟新的空间,有没有清除,所以会超出空间限制哦~
/**
* Definition of ListNode* class ListNode {
* public:
* int val;
* ListNode *next;
* ListNode(int val) {
* this->val = val;
* this->next = NULL;
* }
* }
*/
class Solution {
public:
/**
* @param lists: a list of ListNode
* @return: The head of one sorted list.
*/
// write your code here
ListNode * mergeTwoLists(ListNode * l1, ListNode * l2) {
// write your code here
if(l1 == NULL){
return l2;
}
if (l2 == NULL){
return l1;
}
if(l1->val > l2->val){
ListNode *temp = l1;
l1 = l2;
l2 = temp;
}
ListNode *head = l1;
ListNode *q = l2;
while (l2 != NULL && l1->next != NULL){
if (l1->val <= l2->val && l1->next->val >= l2->val){
q = q->next;
l2->next = l1->next;
l1->next = l2;
l1 = l1->next;
l2 = q;
}
else{
l1 = l1->next;
}
}
if (l2 != NULL){
l1->next = l2;
}
return head;
}
ListNode *mergeKLists(vector<ListNode *> &lists) {
// write your code here
ListNode *l1 = NULL;
ListNode *l2 = NULL;
for(auto c : lists){
l2 = c;
l1 = mergeTwoLists(l1,l2);
}
return l1;
}
};