148 排序链表
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/sort-list
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
题目描述
在 O(n log n) 时间复杂度和常数级空间复杂度下,对链表进行排序。
示例 1:
输入: 4->2->1->3
输出: 1->2->3->4
示例 2:
输入: -1->5->3->4->0
输出: -1->0->3->4->5
题目给出的接口为:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* sortList(ListNode* head) {
}
};
题目分析
使用归并排序,将链表分割为单一的元素,再逐步回溯排序为完整的链表。
代码如下:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* sortList(ListNode* head) {
if(!head || !head -> next) return head;
ListNode *slow = head , *fast = head , * pre = head ;
while(fast && fast -> next)
{
pre = slow;
slow = slow -> next;
fast = fast -> next -> next;
}
pre -> next = NULL;
return mergesort(sortList(head), sortList(slow));
}
ListNode * mergesort(ListNode * l1, ListNode * l2)
{
if(!l1) return l2;
if(!l2) return l1;
if(l1 -> val < l2 -> val)
{
l1 -> next = mergesort(l1 -> next , l2);
return l1;
}
else
{
l2 -> next = mergesort(l2 -> next , l1);
return l2;
}
}
};