Skip to content

Commit 6625fce

Browse files
committed
Create 0725-split-linked-list-in-parts
1 parent 94bbd8b commit 6625fce

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
class Solution {
2+
public ListNode[] splitListToParts(ListNode head, int k) {
3+
int numNodes = countNodes(head);
4+
ListNode[] ans = new ListNode[k];
5+
6+
int remainder = numNodes % k;
7+
int base_len = numNodes / k;
8+
ListNode curr = head;
9+
10+
for (int i = 0; i < k; i++) {
11+
ListNode dummy = new ListNode(0), currHead = dummy;
12+
for (int j = 0; j < base_len + (i < remainder ? 1 : 0); j++) {
13+
currHead = currHead.next = new ListNode(curr.val);
14+
if (curr != null) curr = curr.next;
15+
}
16+
ans[i] = dummy.next;
17+
}
18+
return ans;
19+
}
20+
21+
private int countNodes(ListNode root) {
22+
int cnt = 0;
23+
while (root != null) {
24+
cnt++;
25+
root = root.next;
26+
}
27+
return cnt;
28+
}
29+
}

0 commit comments

Comments
 (0)