forked from AnasImloul/Leetcode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSplit Linked List in Parts.py
35 lines (30 loc) · 1.12 KB
/
Split Linked List in Parts.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# 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]]:
length = 0
cur = head
while cur:
length += 1
cur = cur.next
# DON'T do following since this makes head become null
# while head:
# length += 1
# head = head.next
# calculate the base size and the number of parts contain extra number
size, extra = length // k, length % k
# create empty list to store split parts
res = [[] for _ in range(k)]
# use two ptrs to split parts
prev, cur = None, head
for i in range(k):
res[i] = cur
# if this part contains extra number, it has (size+1) number
for j in range(size + (1 if extra > 0 else 0)):
prev, cur = cur, cur.next
if prev: prev.next = None
extra -= 1
return res