DAY 29
0

# 725. Split Linked List in Parts

## 題目解釋

1. 相鄰的兩段鏈結串列長度不能超過1個
2. 前面的鏈結長度必須大於等於後面的鏈結長度
3. 數字並須要保有原來的順序

## 解法

`k=3, N=10`作為例子，我們的鏈結長度就會分別是4,3,3

### 程式碼

``````class Solution:
def splitListToParts(self, head: Optional[ListNode], k: int) -> List[Optional[ListNode]]:

N = 0
while node:
N += 1
node = node.next

D = N // k
M = N % k

ans = []
# node1是留來斷開鏈結的
for i in range(M):
root = node2
for i in range(D+1):
if node2:
node1 = node2
node2 = node2.next

node1.next = None
ans.append(root)

node1, node2 = ListNode(node2), node2
for i in range(k - M):
root = node2
for i in range(D):
if node2:
node1 = node2
node2 = node2.next

node1.next = None
ans.append(root)

return ans
``````

### 稍微好看一點的版本

``````class Solution:
def splitListToParts(self, head: Optional[ListNode], k: int) -> List[Optional[ListNode]]:

N = 0
while node:
N += 1
node = node.next

D = N // k
M = N % k

size = [D+1] * M + [D] * (k - M)
ans = []

for i in size:
root = node
for j in range(i-1):
if node:
node = node.next

ans.append(root)
if node:
node.next ,node = None, node.next

return ans
``````