方法一:
class Solution(object):
def splitListToParts(self, root, k):
"""
:type root: ListNode
:type k: int
:rtype: List[ListNode]
"""
# 题目说了,头结点是root,不是首节点
cur = root
# 统计原链表的长度
length = 0
while cur:
length += 1
cur = cur.next
# 平均长度
avelen = int(length / k)
# 余数
extra = length % k
# 结果中应有extra个长为avalen+1的链表,k-extra个长为avalen的链表。
nodeList = []
"""先截取extra个长度为avelen + 1的链表"""
avelen += 1
while extra > 0:
# 每趟循环前记录头指针
head = root
pre = None
for i in range(avelen):
pre = root
root = root.next
pre.next = None
nodeList.append(head)
extra -= 1
"""再截取k-extra个长度为avelen的链表"""
k = k - (length % k)
avelen -= 1
if avelen == 0:
while k > 0:
nodeList.append(None)
k -= 1
while k > 0:
if root:
head = root
pre = None
for i in range(avelen):
pre = root
root = root.next
pre.next = None
nodeList.append(head)
else:
nodeList.append(None)
k -= 1
return nodeList