在 O(n log n) 时间复杂度和常数级空间复杂度下,对链表进行排序。
示例 1:
输入: 4->2->1->3
输出: 1->2->3->4
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
ListNode* mergeSortList(ListNode *left, ListNode *right)
{
ListNode *pHead = new ListNode (0);
ListNode *pTail = pHead;
while(left && right)
{
if(left->val < right->val)
{
pTail->next = new ListNode (left->val);
left = left->next;
}
else
{
pTail->next = new ListNode (right->val);
right = right->next;
}
pTail = pTail->next;
}
ListNode *pTemp = (left == NULL ? right : left);
while(pTemp)
{
pTail->next = new ListNode (pTemp->val);
pTemp = pTemp->next;
pTail = pTail->next;
}
return pHead->next;
}
public:
ListNode* sortList(ListNode* head) {
if(NULL == head || NULL == head->next) return head;
ListNode *slow = head;
ListNode *fast = head;
while(fast->next && fast->next->next)
{
slow = slow->next;
fast = fast->next->next;
}
ListNode *left = head;
ListNode *right = slow->next;
slow->next = NULL;
ListNode *subLeft = sortList(left);
ListNode *subRight = sortList(right);
return mergeSortList(subLeft, subRight);
}
};
采用归并排序的思想,利用快慢指针找到链表的中间节点,进行排序处理