要求时间复杂度为O(NlogN)
思路:
采用归并排序,因为快速排序操作两个指针,并且会向前走,这里是单链表,所以不方便。
1.使用快慢指针获取中间结点,将链表分成左右均等的两部分。
2.对以head为头的链表和以pSlow为头的结点分别调用归并排序(递归)。
3.对排序之后的两个链表进行归并。
class Solution {
public:
ListNode *sortList(ListNode *head) {
if (head == NULL || head->next == NULL)
return head;
ListNode* pSlow = head;
ListNode* pFast = head;
ListNode* pre = head;
while (pFast&&pFast->next)
{
pre = pSlow;
pSlow = pSlow->next;
pFast = pFast->next;
}
//pSlow找到中间节点
pre->next = NULL;//将链表分开为两部分
return Merage(sortList(head), sortList(pSlow));
}
ListNode* Merage(ListNode* L1, ListNode* L2)
{
ListNode* tmp = new ListNode(-1);
ListNode* pCur = tmp;
while (L1&&L2)
{
if (L1->val < L2->val)
{
pCur->next = L1;
L1 = L1->next;
}
else
{
pCur->next = L2;
L2 = L2->next;
}
pCur = pCur->next;
}
if (L1)
pCur->next = L1;
if (L2)
pCur->next = L2;
return tmp->next;
}
};