File tree 3 files changed +36
-0
lines changed
3 files changed +36
-0
lines changed Original file line number Diff line number Diff line change
1
+ class Solution :
2
+ def sortList (self , head : Optional [ListNode ]) -> Optional [ListNode ]:
3
+ # Base Case: If the list has 0 or 1 elements, it's already sorted
4
+ if not head or not head .next :
5
+ return head
6
+
7
+ # Find the midpoint of the list using slow and fast pointers
8
+ slow , fast = head , head .next
9
+ while fast and fast .next :
10
+ slow = slow .next
11
+ fast = fast .next .next
12
+
13
+ # Split the list into two halves
14
+ mid = slow .next
15
+ slow .next = None
16
+
17
+ # Recursively sort both halves
18
+ left = self .sortList (head )
19
+ right = self .sortList (mid )
20
+
21
+ # Merge the two sorted halves
22
+ dummy = ListNode (0 )
23
+ curr = dummy
24
+ while left and right :
25
+ if left .val < right .val :
26
+ curr .next = left
27
+ left = left .next
28
+ else :
29
+ curr .next = right
30
+ right = right .next
31
+ curr = curr .next
32
+
33
+ # Append any remaining nodes from either half
34
+ curr .next = left or right
35
+
36
+ return dummy .next
You can’t perform that action at this time.
0 commit comments