Given the head of a linked list, return the list after sorting it in ascending order.
To solve the problem efficiently, we can use a sorting algorithm suitable for linked lists, such as Merge Sort, which has O(n log n) time complexity.
#include <iostream>
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;
}
// Step 1: Find the middle point of the list
ListNode* mid = findMiddle(head);
// Step 2: Split the list into two halves
ListNode* right = mid->next;
mid->next = NULL; // Split the list into two halves
// Step 3: Sort each half
ListNode* left = sortList(head);
right = sortList(right);
// Step 4: Merge the sorted halves
return mergeTwoLists(left, right);
}
private:
ListNode* findMiddle(ListNode* head) {
ListNode* slow = head;
ListNode* fast = head->next;
while (fast && fast->next) {
slow = slow->next;
fast = fast->next->next;
}
return slow;
}
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
ListNode dummy(0);
ListNode* tail = &dummy;
while (l1 && l2) {
if (l1->val < l2->val) {
tail->next = l1;
l1 = l1->next;
} else {
tail->next = l2;
l2 = l2->next;
}
tail = tail->next;
}
if (l1) {
tail->next = l1;
} else {
tail->next = l2;
}
return dummy.next;
}
};
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?