Skip to content

Commit 5642e0c

Browse files
authored
Update Split Linked List in Parts.java
1 parent 4b0fa53 commit 5642e0c

File tree

1 file changed

+21
-19
lines changed

1 file changed

+21
-19
lines changed

Medium/Split Linked List in Parts.java

Lines changed: 21 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -7,25 +7,27 @@
77
* ListNode(int val) { this.val = val; }
88
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
99
* }
10-
*/
10+
*/
1111
class Solution {
12-
public ListNode[] splitListToParts(ListNode head, int k) {
13-
ListNode[] arr = new ListNode[k];
14-
int nodeLength = 0;
15-
for (ListNode curr = head; curr != null; curr = curr.next) {
16-
nodeLength++;
12+
public ListNode[] splitListToParts(ListNode head, int k) {
13+
int length = 0;
14+
ListNode curr = head;
15+
while (curr != null) {
16+
length++;
17+
curr = curr.next;
18+
}
19+
ListNode[] splits = new ListNode[k];
20+
int elementsPerPart = length / k;
21+
int partsWithExtra = length % k;
22+
ListNode prev = null;
23+
for (int i = 0; i < k && head != null; i++, partsWithExtra--) {
24+
splits[i] = head;
25+
for (int j = 0; j < elementsPerPart + (partsWithExtra > 0 ? 1 : 0); j++) {
26+
prev = head;
27+
head = head.next;
28+
}
29+
prev.next = null;
30+
}
31+
return splits;
1732
}
18-
int n = nodeLength / k;
19-
int remaining = nodeLength % k;
20-
ListNode prev = null;
21-
for (int i = 0; i < k && head != null; i++, remaining--) {
22-
arr[i] = head;
23-
for (int j = 0; j < n + (remaining > 0 ? 1 : 0); j++) {
24-
prev = head;
25-
head = head.next;
26-
}
27-
prev.next = null;
28-
}
29-
return arr;
30-
}
3133
}

0 commit comments

Comments
 (0)