|
| 1 | +# [Problem 2181: Merge Nodes in Between Zeros](https://leetcode.com/problems/merge-nodes-in-between-zeros/description) |
| 2 | + |
| 3 | +## Initial thoughts (stream-of-consciousness) |
| 4 | +- start off by iterating through the linked list from the head node |
| 5 | +- whenever we encounter a node with a `.val` of 0, start incrementing a running total of node values beginning with the next node |
| 6 | +- when we reach another 0-value node: |
| 7 | + - construct a `ListNode` whose `.val` is the running total (and `.next` is `None`, for now) |
| 8 | + - if this is the first `ListNode` we've created, it's the head node we need to return at the end... |
| 9 | + - ...otherwise, the last node we made needs to point to it -- so set *that* node's `.next` to this new `ListNode` |
| 10 | + - store the newly created `ListNode` so that we can update its `.next` the next time we create a new node (if we do) |
| 11 | + - reset the running total and keep going |
| 12 | +- the last `ListNode` in the input list will have a `.next` of `None`, so we can iterate over the input list using a `while` loop with that as our stopping condition. |
| 13 | + - but since that will break the loop before we can create the last `ListNode` from the current running total, we'll need to create the last one after the loop breaks |
| 14 | + |
| 15 | +## Refining the problem |
| 16 | + |
| 17 | +## Attempted solution(s) |
| 18 | +```python |
| 19 | +# Definition for singly-linked list. |
| 20 | +class ListNode: |
| 21 | + def __init__(self, val=0, next=None): |
| 22 | + self.val = val |
| 23 | + self.next = next |
| 24 | + |
| 25 | + |
| 26 | +class Solution: |
| 27 | + def mergeNodes(self, head: Optional[ListNode]) -> Optional[ListNode]: |
| 28 | + curr_input_node = head.next |
| 29 | + curr_sum = 0 |
| 30 | + while curr_input_node.next is not None: |
| 31 | + if curr_input_node.val == 0: |
| 32 | + new_merged_node = ListNode(val=curr_sum) |
| 33 | + try: |
| 34 | + prev_merged_node.next = new_merged_node |
| 35 | + except NameError: |
| 36 | + new_head_node = new_merged_node |
| 37 | + curr_sum = 0 |
| 38 | + prev_merged_node = new_merged_node |
| 39 | + else: |
| 40 | + curr_sum += curr_input_node.val |
| 41 | + |
| 42 | + curr_input_node = curr_input_node.next |
| 43 | + |
| 44 | + try: |
| 45 | + prev_merged_node.next = ListNode(val=curr_sum) |
| 46 | + except NameError: |
| 47 | + new_head_node = ListNode(val=curr_sum) |
| 48 | + |
| 49 | + return new_head_node |
| 50 | +``` |
| 51 | + |
| 52 | + |
| 53 | + |
| 54 | +That's kinda slow... there's definitely a more efficient way to do this; might revisit this one at some point. |
0 commit comments