| | 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.SplitLinkedListInParts; |
| | 15 | |
|
| | 16 | | /// <inheritdoc /> |
| | 17 | | public class SplitLinkedListInPartsIterative : ISplitLinkedListInParts |
| | 18 | | { |
| | 19 | | /// <summary> |
| | 20 | | /// Time complexity - O(n) |
| | 21 | | /// Space complexity - O(1) |
| | 22 | | /// </summary> |
| | 23 | | /// <param name="head"></param> |
| | 24 | | /// <param name="k"></param> |
| | 25 | | /// <returns></returns> |
| | 26 | | public ListNode?[] SplitListToParts(ListNode? head, int k) |
| 3 | 27 | | { |
| 3 | 28 | | if (head == null) |
| 1 | 29 | | { |
| 1 | 30 | | return new ListNode[k]; |
| | 31 | | } |
| | 32 | |
|
| 2 | 33 | | var length = 0; |
| 2 | 34 | | var currentNode = head; |
| | 35 | |
|
| 15 | 36 | | while (currentNode != null) |
| 13 | 37 | | { |
| 13 | 38 | | length++; |
| | 39 | |
|
| 13 | 40 | | currentNode = currentNode.next; |
| 13 | 41 | | } |
| | 42 | |
|
| 2 | 43 | | var partSize = length / k; |
| 2 | 44 | | var extraNodesCount = length % k; |
| | 45 | |
|
| 2 | 46 | | var result = new ListNode?[k]; |
| | 47 | |
|
| 2 | 48 | | currentNode = head; |
| | 49 | |
|
| 16 | 50 | | for (var i = 0; i < k && currentNode != null; i++) |
| 6 | 51 | | { |
| 6 | 52 | | result[i] = currentNode; |
| | 53 | |
|
| 6 | 54 | | var currentPartSize = partSize; |
| | 55 | |
|
| 6 | 56 | | if (extraNodesCount > 0) |
| 4 | 57 | | { |
| 4 | 58 | | currentPartSize++; |
| | 59 | |
|
| 4 | 60 | | extraNodesCount--; |
| 4 | 61 | | } |
| | 62 | |
|
| 26 | 63 | | for (var j = 0; j < currentPartSize - 1; j++) |
| 7 | 64 | | { |
| 7 | 65 | | currentNode = currentNode?.next; |
| 7 | 66 | | } |
| | 67 | |
|
| 6 | 68 | | var nextPart = currentNode?.next; |
| | 69 | |
|
| 6 | 70 | | if (currentNode != null) |
| 6 | 71 | | { |
| 6 | 72 | | currentNode.next = null; |
| 6 | 73 | | } |
| | 74 | |
|
| 6 | 75 | | currentNode = nextPart; |
| 6 | 76 | | } |
| | 77 | |
|
| 2 | 78 | | return result; |
| 3 | 79 | | } |
| | 80 | | } |