54 lines
1.2 KiB
Java
54 lines
1.2 KiB
Java
/*
|
|
* @lc app=leetcode id=725 lang=java
|
|
*
|
|
* [725] Split Linked List in Parts
|
|
*/
|
|
|
|
// @lc code=start
|
|
/**
|
|
* Definition for singly-linked list.
|
|
* public class ListNode {
|
|
* int val;
|
|
* ListNode next;
|
|
* ListNode() {}
|
|
* ListNode(int val) { this.val = val; }
|
|
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
|
|
* }
|
|
*/
|
|
class Solution {
|
|
public ListNode[] splitListToParts(ListNode head, int k) {
|
|
int l = len(head);
|
|
int n = l / k, m = l % k, j = 0;
|
|
ListNode cur = head;
|
|
ListNode[] r = new ListNode[k];
|
|
for(int i = 0; i<k; i++) {
|
|
int p = n;
|
|
if(j < m) {
|
|
j++;
|
|
p++;
|
|
}
|
|
r[i] = cur;
|
|
if(p>0) {
|
|
for(int u = 0; u < p-1; u++) {
|
|
cur = cur.next;
|
|
}
|
|
ListNode tmp = cur.next;
|
|
cur.next = null;
|
|
cur = tmp;
|
|
}
|
|
}
|
|
return r;
|
|
}
|
|
|
|
private int len(ListNode head) {
|
|
int r = 0;
|
|
while(head != null) {
|
|
r++;
|
|
head = head.next;
|
|
}
|
|
return r;
|
|
}
|
|
}
|
|
// @lc code=end
|
|
|