Skip to content

Commit d4cae51

Browse files
authored
Update 148-sort-list.js
1 parent cae80b9 commit d4cae51

File tree

1 file changed

+35
-37
lines changed

1 file changed

+35
-37
lines changed

148-sort-list.js

Lines changed: 35 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -48,53 +48,51 @@ function partition(head, tail) {
4848

4949
/**
5050
* 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)
5454
* }
5555
*/
5656
/**
5757
* @param {ListNode} head
5858
* @return {ListNode}
5959
*/
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)
7572
}
7673

77-
7874
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
9084
}
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
9896
}
9997

10098

0 commit comments

Comments
 (0)