725 Split Linked List in Parts
Python
class Solution(object):
def splitListToParts(self, root, k):
"""
:type root: ListNode
:type k: int
:rtype: List[ListNode]
"""
length = 0
curr = root
while curr:
length +=1
curr = curr.next
width = length / k
remainder = length % k
ans = []
cur = root
for i in xrange(k):
head = write = ListNode(None)
for j in xrange(width + (i < remainder)):
write.next = write = ListNode(cur.val)
if cur:
cur = cur.next
ans.append(head.next)
return ans
Java
class Solution {
public ListNode[] splitListToParts(ListNode root, int k) {
ListNode cur = root;
int N = 0;
while (cur != null) {
cur = cur.next;
N++;
}
int width = N / k, rem = N % k;
ListNode[] ans = new ListNode[k];
cur = root;
for (int i = 0; i < k; ++i) {
ListNode head = new ListNode(0), write = head;
for (int j = 0; j < width + (i < rem ? 1 : 0); ++j) {
write = write.next = new ListNode(cur.val);
if (cur != null) cur = cur.next;
}
ans[i] = head.next;
}
return ans;
}
}
编程注意事项
- Java 和 Python 连续赋值的问题
- Java 连续赋值: 自右向左逐一赋值
- Python 连续赋值:从左向右