-
-
Notifications
You must be signed in to change notification settings - Fork 48
Expand file tree
/
Copy path0725-split-linked-list-in-parts.py
More file actions
44 lines (37 loc) · 1.04 KB
/
0725-split-linked-list-in-parts.py
File metadata and controls
44 lines (37 loc) · 1.04 KB
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
# time complexity: O(n)
# space complexity: O(1)
from typing import List, Optional
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]]:
result = [None] * k
curr = head
count = 0
while curr:
curr = curr.next
count += 1
width, remainder = divmod(count, k)
curr = head
prev = curr
for i in range(k):
new = curr
currSize = width
if remainder > 0:
remainder -= 1
currSize += 1
for _ in range(currSize):
prev = curr
if curr:
curr = curr.next
if prev is not None:
prev.next = None
result[i] = new
return result
node = ListNode(1)
node.next = ListNode(2)
node.next.next = ListNode(3)
k = 5
print(Solution().splitListToParts(node, k))