| 8 | |
| 9 | |
| 10 | public class Solution { |
| 11 | public ListNode sortList(ListNode head) { |
| 12 | if (head == null || head.next == null) { |
| 13 | return head; |
| 14 | } |
| 15 | |
| 16 | // Split the list into two halves |
| 17 | ListNode mid = getMid(head); |
| 18 | ListNode left = sortList(head); // sort the first half |
| 19 | ListNode right = sortList(mid); // sort the second half |
| 20 | |
| 21 | // Merge the sorted halves |
| 22 | return merge(left, right); |
| 23 | } |
| 24 | |
| 25 | // Function to find the middle of the list |
| 26 | private ListNode getMid(ListNode head) { |
| 27 | ListNode prev = null; |
| 28 | while (head != null && head.next != null) { |
| 29 | prev = (prev == null) ? head : prev.next; |
| 30 | head = head.next.next; |
| 31 | } |
| 32 | ListNode mid = prev.next; |
| 33 | prev.next = null; // Split the list into two halves |
| 34 | return mid; |
| 35 | } |
| 36 | |
| 37 | // Function to merge two sorted lists |
| 38 | private ListNode merge(ListNode list1, ListNode list2) { |
| 39 | ListNode dummy = new ListNode(0); |
| 40 | ListNode tail = dummy; |
| 41 | |
| 42 | while (list1 != null && list2 != null) { |
| 43 | if (list1.val < list2.val) { |
| 44 | tail.next = list1; |
| 45 | list1 = list1.next; |
| 46 | } else { |
| 47 | tail.next = list2; |
| 48 | list2 = list2.next; |
| 49 | } |
| 50 | tail = tail.next; |
| 51 | } |
| 52 | |
| 53 | // Append the remaining nodes of list1 or list2 |
| 54 | tail.next = (list1 != null) ? list1 : list2; |
| 55 | |
| 56 | return dummy.next; |
| 57 | } |
| 58 | } |
nothing calls this directly
no outgoing calls
no test coverage detected