⚡Flashcard Drill➔
NeetCode #316LC-2181MediumLinked List
← Back to All Problems

#316 · #2181 · Merge Nodes in Between Zeros(合并零之间的节点)

📌 Problem Statement & Constraints

You are given the head of a linked list where consecutive sequences of nodes are separated by nodes with value 0, and the list begins and ends with 0. Merge each sequence between two zeros into a single node holding the sum, and return the modified list. Constraints: 3 <= number of nodes <= 10^5, 0 <= Node.val <= 1000.

💡 Core Algorithmic Approaches

  1. Walk the list; whenever a 0 is encountered, start accumulating the following values until the next 0.
  2. Append a single node with the accumulated sum to the result.
  3. The list starts and ends with 0, so every accumulated segment is properly delimited.
  4. Build the result with a dummy head to avoid special-casing the first segment.

💻 Benchmark Python3 Implementation

class Solution:
    def mergeNodes(self, head: Optional[ListNode]) -> Optional[ListNode]:
        dummy = tail = ListNode(0)
        cur = head
        while cur:
            if cur.val == 0:
                total = 0
                cur = cur.next
                while cur and cur.val != 0:
                    total += cur.val
                    cur = cur.next
                if cur:                    # a closing zero exists -> valid segment
                    tail.next = ListNode(total)
                    tail = tail.next
            else:
                cur = cur.next
        return dummy.next

⚡ Complexity Deep Dive

⏱️ Time Complexity
O(n): each node is visited once.
💾 Space Complexity
O(1) beyond the output (the new nodes are the result).

⚠️ Interview Pitfalls & Follow-ups

  • Forgetting the closing-zero check: the final 0 has no following segment, so an extra zero-sum node would be appended.
  • Summing the zeros themselves: only the values between zeros should be summed.
  • Modifying the input nodes in place: building new nodes is simpler, though in-place modification is also accepted.
  • Assuming the list does not start with 0: the statement guarantees it does, which makes the delimiter logic uniform.
⚡
Test muscle memory on this topic via 3-Layer Flashcards
Active Recall: Mentally formulate Prompt ➔ Math Derivation ➔ Benchmark Implementation in 3 minutes.
🎯 Drill This Card Now➔

🧩 Related Linked List Problems

中文速览与面试要点

合并零之间的节点

给你一个链表的头节点 head,该链表包含由 0 分隔开的一连串整数。链表的 开端 和 末尾 的节点都满足 Node.val == 0 。对于每两个相邻的 0,请你将它们之间的所有节点合并成一个节点,其值是所有已合并节点的值之和。然后将所有 0 移除,修改后的链表不应该含有任何 0。返回修改后链表的头节点 head。约束:3 ≤ 节点总数 ≤ 2 × 10^5;0 ≤ Node.val ≤ 1000。

核心要点

  • 一次遍历累加(标准解) :从 head.next 开始遍历,维护当前段的累加和 s 。遇到值为 0 的节点时,说明一段结束,创建新节点(值为 s)接到结果链表尾部,并把 s 重置为 0。
  • 为什么从 head.next 开始 :头节点必然是 0(段的开始标记),无需处理。
  • 为什么末尾的 0 也会触发创建 :题目保证末尾也是 0,因此最后一段的和会在遇到末尾 0 时被创建。
  • 哑结点 :用于收集结果,避免头节点分支。

常见陷阱

  • 从 head 开始遍历 :开头的 0 会触发一次「创建值为 0 的节点」,产生多余的 0 节点。
  • 在循环结束后再补一段 :题目保证末尾是 0,因此最后一段已在遇到末尾 0 时创建,无需额外处理。若题目不保证,则需要额外判断 if s: ... 。
  • 忘记重置 s = 0 :会导致下一段的和包含上一段。
  • 原地修改节点值而不新建节点 :也可以(把当前 0 节点的值改为 s,然后调整指针),但需要更复杂的指针操作,新建节点更简洁。

参考实现

class Solution:
    def mergeNodes(self, head: 'ListNode') -> 'ListNode':
        dummy = ListNode()
        tail = dummy
        cur = head.next         # 跳过开头的 0
        s = 0
        while cur:
            if cur.val == 0:
                tail.next = ListNode(s)     # 一段结束,创建新节点
                tail = tail.next
                s = 0
            else:
                s += cur.val
            cur = cur.next
        return dummy.next