@@ -48,53 +48,51 @@ function partition(head, tail) {
48
48
49
49
/**
50
50
* Definition for singly-linked list.
51
- * function ListNode(val) {
52
- * this.val = val;
53
- * this.next = null;
51
+ * function ListNode(val, next ) {
52
+ * this.val = ( val===undefined ? 0 : val)
53
+ * this.next = (next===undefined ? null : next)
54
54
* }
55
55
*/
56
56
/**
57
57
* @param {ListNode } head
58
58
* @return {ListNode }
59
59
*/
60
-
61
- const sortList = function ( head ) {
62
- if ( ! head || ! head . next ) return head ;
63
- let fast = head ;
64
- let slow = head ;
65
- let pre = null ;
66
- while ( fast && fast . next ) {
67
- pre = slow ;
68
- fast = fast . next . next ;
69
- slow = slow . next ;
70
- }
71
- pre . next = null ;
72
- const left = sortList ( head ) ;
73
- const right = sortList ( slow ) ;
74
- return merge ( left , right ) ;
60
+ function sortList ( head ) {
61
+ if ( head == null || head . next == null ) return head
62
+ let slow = head , fast = head , pre = null
63
+ while ( fast && fast . next ) {
64
+ pre = slow
65
+ slow = slow . next
66
+ fast = fast . next . next
67
+ }
68
+ pre . next = null
69
+ const left = sortList ( head )
70
+ const right = sortList ( slow )
71
+ return merge ( left , right )
75
72
}
76
73
77
-
78
74
function merge ( left , right ) {
79
- const dummy = new ListNode ( 0 ) ;
80
- let list = dummy
81
- while ( left && right ) {
82
- if ( left . val < right . val ) {
83
- list . next = left ;
84
- left = left . next ;
85
- } else {
86
- list . next = right ;
87
- right = right . next ;
88
- }
89
- list = list . next ;
75
+ const dummy = new ListNode ( )
76
+ let cur = dummy
77
+ while ( left && right ) {
78
+ if ( left . val <= right . val ) {
79
+ cur . next = left
80
+ left = left . next
81
+ } else {
82
+ cur . next = right
83
+ right = right . next
90
84
}
91
- if ( left ) {
92
- list . next = left ;
93
- }
94
- if ( right ) {
95
- list . next = right ;
96
- }
97
- return dummy . next ;
85
+ cur = cur . next
86
+ }
87
+ if ( left ) {
88
+ cur . next = left
89
+ }
90
+
91
+ if ( right ) {
92
+ cur . next = right
93
+ }
94
+
95
+ return dummy . next
98
96
}
99
97
100
98
0 commit comments