File tree 1 file changed +34
-0
lines changed
1 file changed +34
-0
lines changed Original file line number Diff line number Diff line change
1
+ class Solution {
2
+ public ListNode sortList (ListNode head ) {
3
+ if (head == null || head .next == null ) return head ;
4
+ int len = 0 ;
5
+ ListNode cur = head ;
6
+ while (cur != null ){
7
+ len ++;
8
+ cur = cur .next ;
9
+ }
10
+ ListNode left = head ,right = head ;
11
+ for (int i = 0 ; i < len /2 - 1 ; i ++) right = right .next ;
12
+ ListNode leftTail = right ;
13
+ right = right .next ;
14
+ leftTail .next = null ;
15
+ left = sortList (left );
16
+ right = sortList (right );
17
+ ListNode dummy = new ListNode (0 );
18
+ cur = dummy ;
19
+ while (left != null && right != null ){
20
+ if (left .val < right .val ){
21
+ cur .next = left ;
22
+ left = left .next ;
23
+ }else {
24
+ cur .next = right ;
25
+ right = right .next ;
26
+ }
27
+ cur = cur .next ;
28
+ }
29
+ if (left != null ) cur .next = left ;
30
+ else if (right != null ) cur .next = right ;
31
+ else cur .next = null ;
32
+ return dummy .next ;
33
+ }
34
+ }
You can’t perform that action at this time.
0 commit comments