-
Notifications
You must be signed in to change notification settings - Fork 8
/
SplitLinkedListInParts.java
79 lines (67 loc) · 1.85 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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
package linkedlist;
// Source : https://leetcode.com/problems/split-linked-list-in-parts/
// Id : 725
// Author : Fanlu Hai | https://github.com/Fanlu91/FanluLeetcode
// Date : 2019-06-04
// Topic : Linked list
// Other :
// Tips :
// Result : 100.00% 100.00%
public class SplitLinkedListInParts {
// 100.00% 100.00%
public ListNode[] splitListToParts(ListNode root, int k) {
if (root == null) {
return new ListNode[k];
}
int length = getLength(root);
int quotient = length / k;
int remainder = length % k;
ListNode[] array = new ListNode[k];
ListNode tmp = root;
ListNode pre = null;
for (int i = 0; i < remainder; i++) {
if (tmp == null) {
array[i] = null;
} else {
array[i] = tmp;
for (int j = 0; j < quotient + 1; j++) {
if (tmp == null)
break;
pre = tmp;
tmp = tmp.next;
}
pre.next = null;
}
}
for (int i = remainder; i < k; i++) {
if (tmp == null) {
array[i] = null;
} else {
array[i] = tmp;
for (int j = 0; j < quotient; j++) {
if (tmp == null)
break;
pre = tmp;
tmp = tmp.next;
}
pre.next = null;
}
}
return array;
}
public int getLength(ListNode root) {
int length = 1;
while (root.next != null) {
length++;
root = root.next;
}
return length;
}
class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
}
}
}