-
Notifications
You must be signed in to change notification settings - Fork 0
/
SplitLinkedListinParts.java
51 lines (39 loc) · 1.07 KB
/
SplitLinkedListinParts.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
package linkedlist;
public class SplitLinkedListinParts {
public static void main(String[] args) {
}
public ListNode[] splitListToParts(ListNode root, int k) {
ListNode node = root;
int len = len(node);
ListNode[] ret = new ListNode[k];
if(len == 0) return ret;
int size = len / k;
int extra = len % k;
while(k-- > 0){
ListNode n = new ListNode(node.val);
ret[ret.length - k - 1] = n;
int count = size + (extra-- > 0? 1 : 0);
while(count-- > 0){
node = node.next;
if(count > 0 && node != null){
n.next = new ListNode(node.val);
n = n.next;
}else{
break;
}
}
if(node == null){
break;
}
}
return ret;
}
private int len(ListNode node){
int len = 0;
while(node != null){
node = node.next;
len++;
}
return len;
}
}