-
Notifications
You must be signed in to change notification settings - Fork 0
/
725.split-linked-list-in-parts.java
71 lines (57 loc) · 1.58 KB
/
725.split-linked-list-in-parts.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
/**
* 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 {
int i;
public ListNode[] splitListToParts(ListNode head, int k) {
int len = getLength(head);
ListNode[] res = new ListNode[k];
int firstSize = len/k + (len%k);
if(k >= len){
firstSize = 1;
k=1;
len =1;
}
i = 0;
ListNode next = null;
if(len%k != 0){
next = solve(head, (len/k)+1, len%k, res);
solve(next, len/k, 1001, res);
}else
solve(head, (len/k), 1001, res);
return res;
}
public int getLength(ListNode node){
int i = 0;
while(node != null){
node = node.next;
i++;
}
return i;
}
public ListNode solve(ListNode head, int len, int rem, ListNode[] res){
ListNode next = head;
ListNode start = next;
int st = 1;
while(next != null && rem > 0){
if(st%(len) == 0){
res[i++] = start;
start = next;
next = next.next;
start.next = null;
start = next;
rem--;
}else
next = next.next;
st++;
}
return next;
}
}