0
点赞
收藏
分享

微信扫一扫

8道链表常考题-排序链表归并

爱读书的歌者 2022-07-28 阅读 68


8道链表常考题-排序链表归并_leetcode


8道链表常考题-排序链表归并_i++_02


8道链表常考题-排序链表归并_i++_03


8道链表常考题-排序链表归并_i++_04


8道链表常考题-排序链表归并_leetcode_05

8道链表常考题-排序链表归并_i++_06


8道链表常考题-排序链表归并_leetcode_07


​​https://leetcode-cn.com/problems/merge-k-sorted-lists/​​

8道链表常考题-排序链表归并_leetcode_08


8道链表常考题-排序链表归并_i++_09


8道链表常考题-排序链表归并_i++_10


8道链表常考题-排序链表归并_i++_11


8道链表常考题-排序链表归并_leetcode_12


8道链表常考题-排序链表归并_i++_13


8道链表常考题-排序链表归并_leetcode_14

/**
* 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 newhead(0);
ListNode* newtail = &newhead;
while(l1 && l2){
if(l1->val < l2->val){
newtail->next = l1;
l1 = l1->next;
}else{
newtail->next = l2;
l2 = l2->next;
}
newtail = newtail->next;
}
if(l1){
newtail->next = l1;
}
if(l2){
newtail->next = l2;
}
return newhead.next;
}
ListNode* mergeKLists(vector<ListNode*>& lists) {
//截止条件
if(lists.size() == 0) return NULL;
if(lists.size() == 1) return lists[0];
if(lists.size() == 2) return mergeTwoLists(lists[0],lists[1]);

//拆分
int mid = lists.size()/2;
std::vector<ListNode*> sub1_lists;
std::vector<ListNode*> sub2_lists;
for(int i = 0; i < mid; i++){
sub1_lists.push_back(lists[i]);
}
for(int i = mid; i < lists.size(); i++){
sub2_lists.push_back(lists[i]);
}
ListNode* l1 = mergeKLists(sub1_lists);
ListNode* l2 = mergeKLists(sub2_lists);

return mergeTwoLists(l1,l2);
}
};

class Solution {
public:
ListNode* mergeKLists(vector<ListNode*>& lists) {
if (lists.size() == 0) return nullptr;
int n = lists.size();
while (n > 1) {
int k = (n + 1) / 2;
for (int i = 0; i < n / 2; ++i) {
lists[i] = mergeTwoLists(lists[i], lists[i + k]);
}
n = k;
}
return lists[0];
}
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
ListNode dummy(-1);
ListNode *p = &dummy;
while(1){
if(l1==nullptr){
p->next = l2;
break;
}
if(l2==nullptr){
p->next = l1;
break;
}
if(l1->val < l2->val){
p->next = l1;
l1 = l1->next;
p = p->next;
}else{
p->next = l2;
l2 = l2->next;
p = p->next;
}
}
return dummy.next;
}
};


举报

相关推荐

0 条评论