Given the head of a linked list, return the list after sorting it in ascending order.
Input: head = [4,2,1,3]
Output: [1,2,3,4]
**Input:**head = [-1,5,3,4,0]
Output: [-1,0,3,4,5]
Input: head = []
Output: []
From: LeetCode
Link: 148. Sort List
1. Divide the List: The main idea is to split the list into two halves, sort each half, and then merge the sorted halves back together. This is a recursive approach.
2. Find the Middle:
3. Recursive Sort:
4. Merge Sorted Lists:
5. Completing the Merge:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* merge(struct ListNode* l1, struct ListNode* l2) {
struct ListNode* dummy = (struct ListNode*)malloc(sizeof(struct ListNode));
struct ListNode* current = dummy;
while (l1 && l2) {
if (l1->val < l2->val) {
current->next = l1;
l1 = l1->next;
} else {
current->next = l2;
l2 = l2->next;
}
current = current->next;a
}
if (l1) current->next = l1;
if (l2) current->next = l2;
return dummy->next;
}
struct ListNode* findMiddle(struct ListNode* head) {
struct ListNode* prev = NULL;
struct ListNode* slow = head;
struct ListNode* fast = head;
while (fast && fast->next) {
prev = slow;
slow = slow->next;
fast = fast->next->next;
}
if (prev) prev->next = NULL; // Split the list into two halves
return slow;
}
struct ListNode* sortList(struct ListNode* head) {
if (!head || !head->next) return head; // Base case: if the list is empty or has only one node
struct ListNode* mid = findMiddle(head);
struct ListNode* left = sortList(head);
struct ListNode* right = sortList(mid);
return merge(left, right);
}