# Leetcode每日一题：148.sort-list（链表排序）

// 找到链表中间节点（876. 链表的中间结点）
{
while (fast != nullptr && fast->next != nullptr)
{
slow = slow->next;
fast = fast->next->next;
}
return slow;
}

// 合并两个有序链表（21. 合并两个有序链表）
ListNode *merge(ListNode *h1, ListNode *h2)
{
ListNode *h = new ListNode(-1), *head = h;
while (h1 && h2)
{
if (h1->val < h2->val)
{
h->next = h1;
h1 = h1->next;
}
else
{
h->next = h2;
h2 = h2->next;
}
h = h->next;
}
while (h1)
{
h->next = h1;
h = h->next;
h1 = h1->next;
}
while (h2)
{
h->next = h2;
h = h->next;
h2 = h2->next;
}
h->next = nullptr;
}

{
// 递归结束条件
// 找到链表中间节点并断开链表
midNode->next = nullptr;

// 递归

//合并有序链表
return merge(left, right);
}


    ListNode *sortList(ListNode *head)
{
int len = 0;
int intv = 1; //每次处理的节点数

//得到链表长度
while (h)
{
h = h->next;
len++;
}

ListNode *res = new ListNode(0);

while (intv < len)
{
ListNode *pre = res;
ListNode *h = res->next;
ListNode *h1, *h2; //需要合并的两个子链表头节点
int i;
while (h)
{
h1 = h;
i = intv;
while (i && h)
{
h = h->next;
i = i - 1;
}
// 如果i>0 说明不需要归并，因为h2为空，即intv比链表总个数还多
if (i)
break;
// 否则，进行归并
h2 = h;
i = intv;
while (i && h)
{
h = h->next;
i = i - 1;
}

int c1 = intv;
int c2 = intv - i;

// 合并
while (c1 && c2)
{
if (h1->val < h2->val)
{
pre->next = h1;
h1 = h1->next;
c1 = c1 - 1;
}
else
{
pre->next = h2;
h2 = h2->next;
c2 = c2 - 1;
}
pre = pre->next;
}

pre->next = c1 == 0 ? h2 : h1;

while (c1 > 0 || c2 > 0)
{
pre = pre->next;
c1--;
c2--;
}
pre->next = h;
}

intv = intv << 1;
}
return res->next;
}


08-01 2272

02-11 6378
07-11 5252
02-08 9576
02-23 1741
03-14 30
01-03 3万+
03-16 1万+
07-16 1911
04-06 208
02-28 4008
03-22 41
10-28 3186
01-04 16万+
05-25 4104
02-09 2万+