Skip to content

Commit 4089031

Browse files
committed
Add solution #148
1 parent dddab44 commit 4089031

File tree

2 files changed

+50
-0
lines changed

2 files changed

+50
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -117,6 +117,7 @@
117117
143|[Reorder List](./0143-reorder-list.js)|Medium|
118118
144|[Binary Tree Preorder Traversal](./0144-binary-tree-preorder-traversal.js)|Easy|
119119
145|[Binary Tree Postorder Traversal](./0145-binary-tree-postorder-traversal.js)|Easy|
120+
148|[Sort List](./0148-sort-list.js)|Medium|
120121
149|[Max Points on a Line](./0149-max-points-on-a-line.js)|Hard|
121122
151|[Reverse Words in a String](./0151-reverse-words-in-a-string.js)|Medium|
122123
152|[Maximum Product Subarray](./0152-maximum-product-subarray.js)|Medium|

solutions/0148-sort-list.js

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
/**
2+
* 148. Sort List
3+
* https://leetcode.com/problems/sort-list/
4+
* Difficulty: Medium
5+
*
6+
* Given the head of a linked list, return the list after sorting it in ascending order.
7+
*/
8+
9+
/**
10+
* Definition for singly-linked list.
11+
* function ListNode(val, next) {
12+
* this.val = (val===undefined ? 0 : val)
13+
* this.next = (next===undefined ? null : next)
14+
* }
15+
*/
16+
/**
17+
* @param {ListNode} head
18+
* @return {ListNode}
19+
*/
20+
var sortList = function(head) {
21+
if (!head || !head.next) return head;
22+
let fast = head;
23+
let slow = head;
24+
while (fast.next && fast.next.next) {
25+
fast = fast.next.next;
26+
slow = slow.next;
27+
}
28+
const middle = slow.next;
29+
slow.next = null;
30+
return mergeList(sortList(head), sortList(middle));
31+
};
32+
33+
function mergeList(a, b) {
34+
const ordered = new ListNode(-1);
35+
let list = ordered;
36+
37+
while (a && b) {
38+
list.next = a.val < b.val ? a : b;
39+
list = list.next;
40+
if (a.val < b.val) {
41+
a = a.next;
42+
} else {
43+
b = b.next;
44+
}
45+
}
46+
47+
list.next = a ?? b;
48+
return ordered.next;
49+
}

0 commit comments

Comments
 (0)