File tree 1 file changed +45
-0
lines changed
1 file changed +45
-0
lines changed Original file line number Diff line number Diff line change
1
+ /**
2
+ * Definition for singly-linked list.
3
+ * function ListNode(val) {
4
+ * this.val = val;
5
+ * this.next = null;
6
+ * }
7
+ */
8
+ /**
9
+ * @param {ListNode } root
10
+ * @param {number } k
11
+ * @return {ListNode[] }
12
+ */
13
+ var splitListToParts = function ( root , k ) {
14
+ const result = new Array ( k ) ;
15
+
16
+ let length = 0 ;
17
+ let node = root ;
18
+ while ( node ) {
19
+ length ++ ;
20
+ node = node . next ;
21
+ }
22
+
23
+ const pre = Math . floor ( length / k ) ;
24
+ node = root ;
25
+ for ( let i = 0 ; i < result . length ; i ++ ) {
26
+ if ( ! node ) {
27
+ result [ i ] = null ;
28
+ continue ;
29
+ }
30
+
31
+ let currentLength = pre + ( length % k > i ? 1 : 0 ) ;
32
+ result [ i ] = node ;
33
+ while ( node && currentLength > 1 ) {
34
+ node = node . next ;
35
+ currentLength -- ;
36
+ }
37
+ if ( node ) {
38
+ const next = node . next ;
39
+ node . next = null ;
40
+ node = next ;
41
+ }
42
+ }
43
+
44
+ return result ;
45
+ } ;
You can’t perform that action at this time.
0 commit comments