148. Sort List
Sort a linked list in O(n log n) time using constant space complexity.
Example 1:
Input: 4->2->1->3
Output: 1->2->3->4
Example 2:
Input: -1->5->3->4->0
Output: -1->0->3->4->5
解题思路:
- 找当前链表的中点
- 把当前链表分成两部分
- 合并两链表,即对两链表进行排序
/*
执行用时 : 32 ms, 在Sort List的C提交中击败了91.61% 的用户
内存消耗 : 10.8 MB, 在Sort List的C提交中击败了28.33% 的用户
*/
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* Merge(struct ListNode* left,struct ListNode* right){
if(left == NULL){
return right;
}
if(right == NULL){
return left;
}
if(left->val <= right->val){
left->next = Merge(left->next,right);
return left;
}
else{
right->next = Merge(right->next,left);
return right;
}
}
struct ListNode* MergeSort(struct ListNode* node){
//归并到只有一个结点或没有结点时结束
if(node == NULL || node->next == NULL){
return node;
}
struct ListNode* fast = node;
struct ListNode* slow = node;
struct ListNode* divide = node;
while(fast != NULL && fast->next != NULL){
divide = slow;
slow = slow->next;
fast = fast->next->next;
}
divide->next = NULL;
//自顶向下地递归
struct ListNode* left = MergeSort(node);
struct ListNode* right = MergeSort(slow);
return Merge(left,right);//对分成的两段进行合并
}
struct ListNode* sortList(struct ListNode* head){
//特殊情况
if(head == NULL || head->next == NULL){
return head;
}
return MergeSort(head);
}
LeetCode 21. Merge Two Sorted Lists(合并两个有序链表) -- c语言
https://blog.csdn.net/d_benhua/article/details/90523911
LeetCode 876. Middle of the Linked List(链表的中间结点) -- c语言