Skip to content

2181. Merge Nodes in Between Zeros #1581

Answered by mah-shamim
mah-shamim asked this question in Q&A
Discussion options

You must be logged in to vote

We can follow these steps:

  1. Parse Input Linked List: Read the input linked list and identify segments between zeros.
  2. Sum Segments: For each segment between two zeros, calculate the sum of the nodes.
  3. Create New Linked List: Create a new linked list containing the sums of the segments, with zeros at the start and end.

Let's assume you have a linked list class defined like this:

class ListNode {
    public $val = 0;
    public $next = null;
    function __construct($val = 0, $next = null) {
        $this->val = $val;
        $this->next = $next;
    }
}

Here's how you can implement the solution:

<?php
function mergeNodes($head) {
    $dummy = new ListNode(0);
    $current = $dummy;
    $sum = 

Replies: 1 comment 2 replies

Comment options

You must be logged in to vote
2 replies
@kovatz
Comment options

kovatz Apr 19, 2025
Collaborator

@mah-shamim
Comment options

mah-shamim Apr 19, 2025
Maintainer Author

Answer selected by kovatz
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
question Further information is requested medium Difficulty
2 participants