Skip to content

Commit 1b8631f

Browse files
authored
Create Solution.java
1 parent 11bfec1 commit 1b8631f

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
class Solution {
2+
public ListNode[] splitListToParts(ListNode root, int k) {
3+
ListNode[] res = new ListNode[k];
4+
int n = getLength(root);
5+
int len = n / k, left = n % k;
6+
ListNode pre = null; // 记录链尾
7+
for (int i = 0; i < k && root != null; ++i) {
8+
res[i] = root;
9+
int step = len;
10+
if (left > 0) {
11+
--left;
12+
++step;
13+
}
14+
for (int j = 0; j < step; ++j) {
15+
pre = root;
16+
root = root.next;
17+
}
18+
pre.next = null; // 断链
19+
}
20+
return res;
21+
}
22+
23+
private int getLength(ListNode root) {
24+
int res = 0;
25+
while (root != null) {
26+
++res;
27+
root = root.next;
28+
}
29+
return res;
30+
}
31+
}

0 commit comments

Comments
 (0)