Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Create 0725-split-linked-list-in-parts
  • Loading branch information
benmak11 committed Sep 7, 2023
commit 6625fce3129d995acb9bbee5424b82461134dc7c
29 changes: 29 additions & 0 deletions java/0725-split-linked-list-in-parts.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
class Solution {
public ListNode[] splitListToParts(ListNode head, int k) {
int numNodes = countNodes(head);
ListNode[] ans = new ListNode[k];

int remainder = numNodes % k;
int base_len = numNodes / k;
ListNode curr = head;

for (int i = 0; i < k; i++) {
ListNode dummy = new ListNode(0), currHead = dummy;
for (int j = 0; j < base_len + (i < remainder ? 1 : 0); j++) {
currHead = currHead.next = new ListNode(curr.val);
if (curr != null) curr = curr.next;
}
ans[i] = dummy.next;
}
return ans;
}

private int countNodes(ListNode root) {
int cnt = 0;
while (root != null) {
cnt++;
root = root.next;
}
return cnt;
}
}