Leetcode 725 Solution

This article provides solution to leetcode question 725 (split-linked-list-in-parts)

https://leetcode.com/problems/split-linked-list-in-parts

Solution

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def splitListToParts(self, root: ListNode, k: int) -> List[ListNode]:
        node = root
        length = 0
        while node:
            node = node.next
            length += 1

        l = length // k
        r = length % k

        prev = None
        curr = root
        ans = []
        for i in range(k):
            local_head = curr

            for j in range(l + (1 if r > 0 else 0)):
                if not curr:
                    continue

                prev = curr
                curr = curr.next

            if prev:
                prev.next = None

            ans.append(local_head)
            r = max(r - 1, 0)

        return ans