We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
1 parent 94bbd8b commit 6625fceCopy full SHA for 6625fce
java/0725-split-linked-list-in-parts.java
@@ -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