在 O(n log n) 时间复杂度和常数级空间复杂度下,对链表进行排序。
示例 1:
输入: 4->2->1->3
输出: 1->2->3->4
示例 2:
输入: -1->5->3->4->0
输出: -1->0->3->4->5
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/sort-list
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
方法:
利用归并排序,进行排序。再求中间节点时利用,两个指针fast,slow,fast一次走两个节点而slow走一个节点,当fast走完整个链表时,slow正好处于中间节点上。
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
ListNode* merge(ListNode* l1, ListNode*l2) {
if (!l1) return l2;
if (!l2) return l1;
ListNode head(0);
ListNode* opre = &head;
while (l1 && l2) {
if (l1->val < l2->val) {
opre->next = l1;
opre = l1;
l1 = l1->next;
} else {
opre->next = l2;
opre = l2;
l2 = l2->next;
}
}
opre->next = (l1 ? l1 : l2);
return head.next;
}
public:
ListNode* sortList(ListNode* head) {
if (!head || !head->next)
return head;
ListNode* fast = head;
ListNode* slow = head;
ListNode* pre = head;
while (fast && fast->next) {
fast = fast->next->next;
pre = slow;
slow = slow->next;
}
pre->next = nullptr;
ListNode* L1 = sortList(head);
ListNode* L2 = sortList(slow);
return merge(L1, L2);
}
};