725. Split Linked List in Parts (Medium) - TengnanYao/daily_leetcode GitHub Wiki

# 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: Optional[ListNode], k: int) -> List[Optional[ListNode]]:
        cur = head
        n = 0
        while cur:
            n += 1
            cur = cur.next
        a, b = divmod(n, k)
        result = [None] * k
        cur = head
        for i in range(b):
            result[i] = cur
            for j in range(a):
                cur = cur.next
            temp = cur.next
            cur.next = None
            cur = temp
        if a > 0:
            for i in range(b, k):
                result[i] = cur
                for j in range(a - 1):
                    cur = cur.next
                temp = cur.next
                cur.next = None
                cur = temp
        return result