File tree 1 file changed +68
-0
lines changed
1 file changed +68
-0
lines changed Original file line number Diff line number Diff line change
1
+ public class Solution {
2
+ public ListNode SortList ( ListNode head ) {
3
+ if ( head ? . next == null )
4
+ {
5
+ return head ;
6
+ }
7
+
8
+ ListNode mid = head , cur = head . next ;
9
+ while ( cur != null )
10
+ {
11
+ cur = cur . next ;
12
+
13
+ if ( cur != null )
14
+ {
15
+ cur = cur . next ;
16
+ mid = mid . next ;
17
+ }
18
+ }
19
+
20
+ var first = head ;
21
+ var second = mid . next ;
22
+ mid . next = null ;
23
+
24
+ first = SortList ( first ) ;
25
+ second = SortList ( second ) ;
26
+
27
+ ListNode result = null , resultTail = null ;
28
+
29
+ while ( first != null && second != null )
30
+ {
31
+ if ( first . val < second . val )
32
+ {
33
+ AddToResult ( first ) ;
34
+ first = first . next ;
35
+ }
36
+ else
37
+ {
38
+ AddToResult ( second ) ;
39
+ second = second . next ;
40
+ }
41
+ }
42
+
43
+ if ( first != null )
44
+ {
45
+ AddToResult ( first ) ;
46
+ }
47
+
48
+ if ( second != null )
49
+ {
50
+ AddToResult ( second ) ;
51
+ }
52
+
53
+ void AddToResult ( ListNode node )
54
+ {
55
+ if ( resultTail == null )
56
+ {
57
+ result = resultTail = node ;
58
+ }
59
+ else
60
+ {
61
+ resultTail . next = node ;
62
+ resultTail = node ;
63
+ }
64
+ }
65
+
66
+ return result ;
67
+ }
68
+ }
You can’t perform that action at this time.
0 commit comments