2181. Merge Nodes in Between Zeros #1581
-
Topics: You are given the For every two consecutive Return the Example 1:
Example 2:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We can follow these steps:
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 = 0;
// Skip the first zero node
$head = $head->next;
while ($head !== null) {
if ($head->val == 0) {
$current->next = new ListNode($sum);
$current = $current->next;
$sum = 0;
} else {
$sum += $head->val;
}
$head = $head->next;
}
return $dummy->next;
}
// Helper function to print linked list
function printLinkedList($head) {
$current = $head;
while ($current !== null) {
echo $current->val . " ";
$current = $current->next;
}
echo "\n";
}
// Helper function to create linked list from array
function createLinkedList($arr) {
$dummy = new ListNode(0);
$current = $dummy;
foreach ($arr as $value) {
$current->next = new ListNode($value);
$current = $current->next;
}
return $dummy->next;
}
// Example usage
$input = [0, 3, 1, 0, 4, 5, 2, 0];
$head = createLinkedList($input);
$result = mergeNodes($head);
printLinkedList($result); // Expected output: 4 11
?> Explanation
|
Beta Was this translation helpful? Give feedback.
We can follow these steps:
Let's assume you have a linked list class defined like this:
Here's how you can implement the solution: