直接按照题意的链表做就行了
# Definition for singly-linked list.
from typing import Optional
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def mergeNodes(self, head: Optional[ListNode]) -> Optional[ListNode]:
result_head = ListNode(0, None)
point = None
value = 0
while head:
if head.val == 0 and value != 0:
if not point:
result_head.val = value
point = result_head
else:
node = ListNode(value, None)
point.next = node
point = node
value = 0
else:
value += head.val
head = head.next
return result_head