Skip to content

Commit 1b45de9

Browse files
Create split_linked_list_in_parts.py
1 parent 24ae847 commit 1b45de9

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed

split_linked_list_in_parts.py

+43
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
# Definition for singly-linked list.
2+
# class ListNode:
3+
# def __init__(self, val=0, next=None):
4+
# self.val = val
5+
# self.next = next
6+
class Solution:
7+
def splitListToParts(self, head: ListNode, k: int) -> List[ListNode]:
8+
9+
10+
current, prev = head, ListNode(0)
11+
count = 0
12+
13+
while current:
14+
count += 1
15+
current = current.next
16+
17+
meanSize = count // k # size of each window
18+
moreThanAverageGroups = count % k # number of windows that are +1 than the mean size of every window
19+
20+
parts, current = [], head
21+
22+
for _ in range(k):
23+
if current:
24+
25+
parts.append(current) # append the current head
26+
maxSizeOfWindow = meanSize + 1 if moreThanAverageGroups > 0 else meanSize #check how many to occupy in the new window
27+
28+
moreThanAverageGroups -= 1
29+
30+
for _ in range(maxSizeOfWindow):
31+
prev, current = current, current.next
32+
33+
prev.next = None #end of current list
34+
35+
else:
36+
parts.append(None)
37+
return parts
38+
39+
40+
41+
42+
43+

0 commit comments

Comments
 (0)