|
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 | classSolution {
|
12 |
| -publicListNode[]splitListToParts(ListNodehead,intk) { |
13 |
| -ListNode[]arr =newListNode[k]; |
14 |
| -intnodeLength =0; |
15 |
| -for (ListNodecurr =head;curr !=null;curr =curr.next) { |
16 |
| -nodeLength++; |
| 12 | +publicListNode[]splitListToParts(ListNodehead,intk) { |
| 13 | +intlength =0; |
| 14 | +ListNodecurr =head; |
| 15 | +while (curr !=null) { |
| 16 | +length++; |
| 17 | +curr =curr.next; |
| 18 | + } |
| 19 | +ListNode[]splits =newListNode[k]; |
| 20 | +intelementsPerPart =length /k; |
| 21 | +intpartsWithExtra =length %k; |
| 22 | +ListNodeprev =null; |
| 23 | +for (inti =0;i <k &&head !=null;i++,partsWithExtra--) { |
| 24 | +splits[i] =head; |
| 25 | +for (intj =0;j <elementsPerPart + (partsWithExtra >0 ?1 :0);j++) { |
| 26 | +prev =head; |
| 27 | +head =head.next; |
| 28 | + } |
| 29 | +prev.next =null; |
| 30 | + } |
| 31 | +returnsplits; |
17 | 32 | }
|
18 |
| -intn =nodeLength /k; |
19 |
| -intremaining =nodeLength %k; |
20 |
| -ListNodeprev =null; |
21 |
| -for (inti =0;i <k &&head !=null;i++,remaining--) { |
22 |
| -arr[i] =head; |
23 |
| -for (intj =0;j <n + (remaining >0 ?1 :0);j++) { |
24 |
| -prev =head; |
25 |
| -head =head.next; |
26 |
| - } |
27 |
| -prev.next =null; |
28 |
| - } |
29 |
| -returnarr; |
30 |
| - } |
31 | 33 | }
|