Skip to content

Commit 2392874

Browse files
authored
Update and rename Split Linked List into Parts.java to Split Linked List in Parts.java
1 parent 1a3fe56 commit 2392874

File tree

2 files changed

+31
-44
lines changed

2 files changed

+31
-44
lines changed
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
/**
2+
* Definition for singly-linked list.
3+
* public class ListNode {
4+
* int val;
5+
* ListNode next;
6+
* ListNode() {}
7+
* ListNode(int val) { this.val = val; }
8+
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
9+
* }
10+
*/
11+
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++;
17+
}
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+
}
31+
}

Medium/Split Linked List into Parts.java

Lines changed: 0 additions & 44 deletions
This file was deleted.

0 commit comments

Comments
 (0)