※ 引述《dont (dont)》之铭言:
: 725. Split Linked List in Parts
: ## 思路
: 先计算node的数量,
: 除k得到每堆的node数量, 剩下的余数平均给前r堆
偷懒直接看思路
ListNode真的不懂所以跑去问了ChatGPT
原来 current = head 之后用 current = current.next 不会影响到 head
第一次知道
Python Code:
class Solution:
def splitListToParts(self, head: Optional[ListNode], k: int) -> List[Optional[ListNode]]:
count = 0
ptr = head
while ptr:
count += 1
ptr = ptr.next
part_length, extra = divmod(count, k)
parts = []
current = head
for i in range(k):
current_part_length = part_length + (1 if i < extra else 0)
new_head = new_current = None
while current_part_length > 0 and current:
new_node = ListNode(current.val)
if new_head is None:
new_head = new_node
new_current = new_head
else:
new_current.next = new_node
new_current = new_node
current = current.next
current_part_length -= 1
parts.append(new_head)
return parts
比大师的程式码长好多 哀
https://i.imgur.com/kYDRjbm.png
1 2 还在放弃状态没打到 前天有看题目但不会就放到忘了
再漏一天就不用买票补了 好耶