File tree 1 file changed +21
-19
lines changed
1 file changed +21
-19
lines changed Original file line number Diff line number Diff line change 7
7
* ListNode(int val) { this.val = val; }
8
8
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
9
9
* }
10
- */
10
+ */
11
11
class Solution {
12
- public ListNode [] splitListToParts (ListNode head , int k ) {
13
- ListNode [] arr = new ListNode [k ];
14
- int nodeLength = 0 ;
15
- for (ListNode curr = head ; curr != null ; curr = curr .next ) {
16
- nodeLength ++;
12
+ public ListNode [] splitListToParts (ListNode head , int k ) {
13
+ int length = 0 ;
14
+ ListNode curr = head ;
15
+ while (curr != null ) {
16
+ length ++;
17
+ curr = curr .next ;
18
+ }
19
+ ListNode [] splits = new ListNode [k ];
20
+ int elementsPerPart = length / k ;
21
+ int partsWithExtra = length % k ;
22
+ ListNode prev = null ;
23
+ for (int i = 0 ; i < k && head != null ; i ++, partsWithExtra --) {
24
+ splits [i ] = head ;
25
+ for (int j = 0 ; j < elementsPerPart + (partsWithExtra > 0 ? 1 : 0 ); j ++) {
26
+ prev = head ;
27
+ head = head .next ;
28
+ }
29
+ prev .next = null ;
30
+ }
31
+ return splits ;
17
32
}
18
- int n = nodeLength / k ;
19
- int remaining = nodeLength % k ;
20
- ListNode prev = null ;
21
- for (int i = 0 ; i < k && head != null ; i ++, remaining --) {
22
- arr [i ] = head ;
23
- for (int j = 0 ; j < n + (remaining > 0 ? 1 : 0 ); j ++) {
24
- prev = head ;
25
- head = head .next ;
26
- }
27
- prev .next = null ;
28
- }
29
- return arr ;
30
- }
31
33
}
You can’t perform that action at this time.
0 commit comments