标签:size turn slow 快慢指针 family tno 归并 过程 amp
链表的排序有很多方式,这里记录一下归并排序,关键点2个: 归并排序的过程和快慢指针法找中间结点,直接上代码。
class Solution {
public:
ListNode* sortList(ListNode* head) {
if (!head || !head->next) return head;
ListNode* slow = head, * fast = head->next;
while (fast && fast->next) {
slow = slow->next;
fast = fast->next->next;
}
ListNode* left = sortList(slow->next); // slow 为中间结点了
slow->next = NULL;
ListNode* right = sortList(head);
return merge(left, right);
}
ListNode* merge(ListNode* left, ListNode* right) {
ListNode* dummy = new ListNode(0);
ListNode* p = dummy;
while (left && right) {
if (left->val < right->val) {
p->next = left;
left = left->next;
}
else {
p->next = right;
right = right->next;
}
p = p->next;
}
if (left) p->next = left;
if (right) p->next = right;
return dummy->next;
}
};
标签:size turn slow 快慢指针 family tno 归并 过程 amp
原文地址:https://www.cnblogs.com/E-Dreamer-Blogs/p/12642805.html