1. 合并两个有序链表
class Solution {
public:
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
ListNode* preHead = new ListNode(-1);
//一定要使用头指针并复制一个副本,不然后面循环操作不统一,未合并完的也不好加上去
ListNode* prev = preHead;
while (l1&&l2) {
if (l1->val < l2->val) {
prev->next = l1;//链入pre
l1 = l1->next;//指针后移
} else {
prev->next = l2;
l2 = l2->next;
}
prev = prev->next;//pre指针后移
}
// 合并后 l1 和 l2 最多只有一个还未被合并完,我们直接将链表末尾指向未合并完的链表即可
prev->next = l1 == nullptr ? l2 : l1;
return preHead->next;
}
//也可以使用递归
};
2. 合并k个有序链表
//归并
ListNode* mergeKLists(vector<ListNode*>& lists) {
if(!lists.size()) return {};
return merge(lists,0,lists.size()-1);
}
ListNode* merge(vector<ListNode*>& lists,int i ,int j){
if(i==j) return lists[i];//边界
ListNode*left=merge(lists,i,(i+j)/2);//分治
ListNode*right=merge(lists,(i+j)/2+1,j);//分治
return mergeTwoLists(left,right);//归并
}
//顺序合并
ListNode* mergeKLists(vector<ListNode*>& lists) {
ListNode *ans = nullptr;
for (size_t i = 0; i < lists.size(); ++i) {
ans = mergeTwoLists(ans, lists[i]);
}
return ans;
}
3. 排序链表(归并)
//主函数
ListNode* sortList(ListNode* head) {
// 1、递归结束条件
if (!head||!head->next) return head;
// 2、找到链表中间节点并断开链表(两个返回第一个)
ListNode* midNode = middleNode(head);
ListNode* rightHead = midNode->next;
midNode->next = nullptr;
ListNode* left = sortList(head);//分治
ListNode* right = sortList(rightHead);//分治
// 3、当前层业务操作(合并有序链表)
return mergeTwoLists(left, right);//归并
}
//找中间节点的前一个节点
ListNode* middleNode(ListNode* head) {
if(!head||!head->next) return head;
ListNode* slow = head;
ListNode* fast = head->next->next;
while (fast != NULL && fast->next != NULL) {
slow = slow->next;
fast = fast->next->next;
}
return slow;
}
4. 排序链表(极简归并)
class Solution {
public:
ListNode* sortList(ListNode* head) {
if (!head || !head->next) return head;
auto slow = head, fast = head;
while (fast->next && fast->next->next)
slow = slow->next, fast = fast->next->next;
// 切链
fast = slow->next, slow->next = nullptr;
return merge(sortList(head), sortList(fast));
}
private:
ListNode* merge(ListNode* l1, ListNode* l2) {
ListNode sub(0), *ptr = ⊂
while (l1 && l2) {
auto &node = l1->val < l2->val ? l1 : l2;
ptr = ptr->next = node, node = node->next;
}
ptr->next = l1 ? l1 : l2;
return sub.next;
}
};