| | 1 | | // -------------------------------------------------------------------------------- |
| | 2 | | // Copyright (C) 2025 Eugene Eremeev (also known as Yevhenii Yeriemeieiv). |
| | 3 | | // All Rights Reserved. |
| | 4 | | // -------------------------------------------------------------------------------- |
| | 5 | | // This software is the confidential and proprietary information of Eugene Eremeev |
| | 6 | | // (also known as Yevhenii Yeriemeieiv) ("Confidential Information"). You shall not |
| | 7 | | // disclose such Confidential Information and shall use it only in accordance with |
| | 8 | | // the terms of the license agreement you entered into with Eugene Eremeev (also |
| | 9 | | // known as Yevhenii Yeriemeieiv). |
| | 10 | | // -------------------------------------------------------------------------------- |
| | 11 | |
|
| | 12 | | using LeetCode.Core.Models; |
| | 13 | |
|
| | 14 | | namespace LeetCode.Algorithms.MergeNodesInBetweenZeros; |
| | 15 | |
|
| | 16 | | /// <inheritdoc /> |
| | 17 | | public class MergeNodesInBetweenZerosRecursive : IMergeNodesInBetweenZeros |
| | 18 | | { |
| | 19 | | /// <summary> |
| | 20 | | /// Time complexity - O(n) |
| | 21 | | /// Space complexity - O(n) |
| | 22 | | /// </summary> |
| | 23 | | /// <param name="head"></param> |
| | 24 | | /// <returns></returns> |
| | 25 | | public ListNode? MergeNodes(ListNode? head) |
| 10 | 26 | | { |
| 10 | 27 | | if (head == null) |
| 3 | 28 | | { |
| 3 | 29 | | return null; |
| | 30 | | } |
| | 31 | |
|
| 7 | 32 | | var listNode = head; |
| | 33 | |
|
| 7 | 34 | | if (listNode.val == 0) |
| 7 | 35 | | { |
| 7 | 36 | | var sum = 0; |
| | 37 | |
|
| 7 | 38 | | var zeroNode = listNode.next; |
| | 39 | |
|
| 20 | 40 | | while (zeroNode != null && zeroNode.val != 0) |
| 13 | 41 | | { |
| 13 | 42 | | sum += zeroNode.val; |
| | 43 | |
|
| 13 | 44 | | zeroNode = zeroNode.next; |
| 13 | 45 | | } |
| | 46 | |
|
| 7 | 47 | | listNode.val = sum; |
| 7 | 48 | | listNode.next = zeroNode is null or { val: 0, next: null } ? null : zeroNode; |
| 7 | 49 | | } |
| | 50 | |
|
| 7 | 51 | | listNode = listNode.next; |
| | 52 | |
|
| 7 | 53 | | MergeNodes(listNode); |
| | 54 | |
|
| 7 | 55 | | return head; |
| 10 | 56 | | } |
| | 57 | | } |