1
+ namespace LeetCodeSolutions . DivideAndConquer
2
+ {
3
+ class SortListSolution
4
+ {
5
+ public ListNode SortList ( ListNode head )
6
+ {
7
+ // Base case: empty list or single node is already sorted
8
+ if ( head == null || head . next == null )
9
+ {
10
+ return head ;
11
+ }
12
+
13
+ // Split the list into two halves
14
+ ListNode middle = GetMiddle ( head ) ;
15
+ ListNode right = middle . next ;
16
+ middle . next = null ; // Disconnect the two halves
17
+
18
+ // Recursively sort both halves
19
+ ListNode left = SortList ( head ) ;
20
+ right = SortList ( right ) ;
21
+
22
+ // Merge the sorted halves
23
+ return Merge ( left , right ) ;
24
+ }
25
+
26
+ // Find the middle of the linked list using slow/fast pointers
27
+ private ListNode GetMiddle ( ListNode head )
28
+ {
29
+ ListNode slow = head ;
30
+ ListNode fast = head . next ;
31
+
32
+ while ( fast != null && fast . next != null )
33
+ {
34
+ slow = slow . next ;
35
+ fast = fast . next . next ;
36
+ }
37
+
38
+ return slow ;
39
+ }
40
+
41
+ // Merge two sorted linked lists
42
+ private ListNode Merge ( ListNode left , ListNode right )
43
+ {
44
+ ListNode dummy = new ListNode ( ) ;
45
+ ListNode current = dummy ;
46
+
47
+ // Compare nodes and link them in sorted order
48
+ while ( left != null && right != null )
49
+ {
50
+ if ( left . val < right . val )
51
+ {
52
+ current . next = left ;
53
+ left = left . next ;
54
+ }
55
+ else
56
+ {
57
+ current . next = right ;
58
+ right = right . next ;
59
+ }
60
+
61
+ current = current . next ;
62
+ }
63
+
64
+ // Attach remaining nodes (if any)
65
+ current . next = ( left != null ) ? left : right ;
66
+
67
+ return dummy . next ;
68
+ }
69
+
70
+ [ Test ( Description = "https://leetcode.com/problems/sort-list/" ) ]
71
+ [ Category ( "Medium" ) ]
72
+ [ Category ( "LeetCode" ) ]
73
+ [ Category ( "Sort List" ) ]
74
+ [ TestCaseSource ( nameof ( Input ) ) ]
75
+ [ Category ( "DivideAndConquer" ) ]
76
+ [ Category ( "TopInterview" ) ]
77
+ public void Test1 ( ( int ? [ ] Output , int [ ] Input ) item )
78
+ {
79
+ var response = SortList ( item . Input . ToListNode ( ) ) ;
80
+ Assert . That ( response . ToArray ( ) , Is . EqualTo ( item . Output ) ) ;
81
+ }
82
+
83
+ public static IEnumerable < ( int [ ] Output , int [ ] Input ) > Input =>
84
+ new List < ( int [ ] Output , int [ ] Input ) > ( )
85
+ {
86
+ ( [ - 1 , 0 , 3 , 4 , 5 ] , ( [ - 1 , 5 , 3 , 4 , 0 ] ) ) ,
87
+ } ;
88
+ }
89
+ }
0 commit comments