File tree 2 files changed +50
-0
lines changed
2 files changed +50
-0
lines changed Original file line number Diff line number Diff line change 117
117
143|[ Reorder List] ( ./0143-reorder-list.js ) |Medium|
118
118
144|[ Binary Tree Preorder Traversal] ( ./0144-binary-tree-preorder-traversal.js ) |Easy|
119
119
145|[ Binary Tree Postorder Traversal] ( ./0145-binary-tree-postorder-traversal.js ) |Easy|
120
+ 148|[ Sort List] ( ./0148-sort-list.js ) |Medium|
120
121
149|[ Max Points on a Line] ( ./0149-max-points-on-a-line.js ) |Hard|
121
122
151|[ Reverse Words in a String] ( ./0151-reverse-words-in-a-string.js ) |Medium|
122
123
152|[ Maximum Product Subarray] ( ./0152-maximum-product-subarray.js ) |Medium|
Original file line number Diff line number Diff line change
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
+ }
You can’t perform that action at this time.
0 commit comments