725.分隔链表
题目描述
思路:模拟
先统计链表的长度,然后根据链表的长度和k判断每段的长度(通过除数和余数),除数是每个的基础长度,余数是前多少个需要额外多一个。
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def splitListToParts(self, head: ListNode, k: int) -> List[ListNode]:
cur, l = head, 0
while cur:
l += 1
cur = cur.next
each, remain = l // k, l % k
cur, idx, ans = head, 0, [None] * k
while cur:
ans[idx] = cur
last = None
for i in range(each + (idx < remain)):
last = cur
cur = cur.next
idx += 1
last.next = None
return ans