-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathSplitLinkedListInParts.java
47 lines (46 loc) · 1.22 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
/*https://leetcode.com/problems/split-linked-list-in-parts/*/
/**
* 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 {
public ListNode[] splitListToParts(ListNode head, int k) {
if (head == null) return new ListNode[k];
int copy, N = 0, extra = 0, i;
ListNode tail, temp = head;
while (temp != null)
{
temp = temp.next;
++N;
}
ListNode[] result = new ListNode[k];
extra = N%k;
N /= k;
for (i = 0; i < k; ++i)
{
result[i] = tail = new ListNode(-1);
copy = N;
while (copy-- > 0)
{
tail.next = head;
head = head.next;
tail = tail.next;
}
if (extra-- > 0)
{
tail.next = head;
head = head.next;
tail = tail.next;
}
tail.next = null;
result[i] = result[i].next;
}
return result;
}
}