-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathm725.py
54 lines (42 loc) · 1.47 KB
/
m725.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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
# 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]]:
listLength = 0
curr = head
while curr :
curr = curr.next
listLength += 1
chunkSize = listLength // k
numberOfLargerChunks = listLength - chunkSize * k
numberOfRegularChunks = k - numberOfLargerChunks
output = []
prev = None
curr = head
while curr :
if numberOfLargerChunks :
numberOfLargerChunks -= 1
currentChunkSize = chunkSize + 1
output.append(curr)
if prev :
prev.next = None
for i in range(currentChunkSize) :
prev = curr
curr = curr.next
elif numberOfRegularChunks :
numberOfRegularChunks -= 1
output.append(curr)
if prev :
prev.next = None
for i in range(chunkSize) :
prev = curr
curr = curr.next
else :
break
while numberOfRegularChunks :
output.append(None)
numberOfRegularChunks -= 1
return output