|
| 1 | +class Solution { |
| 2 | +public: |
| 3 | + // Function to merge two sorted linked lists |
| 4 | + Node* merge(Node* left, Node* right) { |
| 5 | + if (!left) return right; |
| 6 | + if (!right) return left; |
| 7 | + |
| 8 | + Node* result = nullptr; |
| 9 | + |
| 10 | + if (left->data <= right->data) { |
| 11 | + result = left; |
| 12 | + result->next = merge(left->next, right); |
| 13 | + } else { |
| 14 | + result = right; |
| 15 | + result->next = merge(left, right->next); |
| 16 | + } |
| 17 | + return result; |
| 18 | + } |
| 19 | + |
| 20 | + // Function to find the middle of the linked list |
| 21 | + Node* getMiddle(Node* head) { |
| 22 | + if (!head) return head; |
| 23 | + |
| 24 | + Node* slow = head; |
| 25 | + Node* fast = head->next; |
| 26 | + |
| 27 | + while (fast && fast->next) { |
| 28 | + slow = slow->next; |
| 29 | + fast = fast->next->next; |
| 30 | + } |
| 31 | + |
| 32 | + return slow; |
| 33 | + } |
| 34 | + |
| 35 | + // Main function to implement merge sort |
| 36 | + Node* mergeSort(Node* head) { |
| 37 | + if (!head || !head->next) return head; |
| 38 | + |
| 39 | + // Find the middle of the linked list |
| 40 | + Node* middle = getMiddle(head); |
| 41 | + Node* nextOfMiddle = middle->next; |
| 42 | + middle->next = nullptr; // Split into two halves |
| 43 | + |
| 44 | + // Recursively sort both halves |
| 45 | + Node* left = mergeSort(head); |
| 46 | + Node* right = mergeSort(nextOfMiddle); |
| 47 | + |
| 48 | + // Merge the two sorted halves |
| 49 | + return merge(left, right); |
| 50 | + } |
| 51 | +}; |
0 commit comments