| | 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 | | // ReSharper disable InconsistentNaming |
| | 13 | |
|
| | 14 | | namespace LeetCode.Core.Models; |
| | 15 | |
|
| | 16 | | /// <summary> |
| | 17 | | /// Definition for singly-linked list |
| | 18 | | /// </summary> |
| | 19 | | public class ListNode |
| | 20 | | { |
| | 21 | | public ListNode? next; |
| | 22 | |
|
| | 23 | | public int val; |
| | 24 | |
|
| 1233 | 25 | | public ListNode(int val = 0, ListNode? next = null) |
| 1233 | 26 | | { |
| 1233 | 27 | | this.next = next; |
| 1233 | 28 | | this.val = val; |
| 1233 | 29 | | } |
| | 30 | |
|
| | 31 | | public static ListNode? ToListNode(int[] array) |
| 343 | 32 | | { |
| 1435 | 33 | | return array.Reverse().Aggregate<int, ListNode?>(null, (next, val) => new ListNode(val, next)); |
| 343 | 34 | | } |
| | 35 | |
|
| | 36 | | public static ListNode? ToCycledListNode(int[] array, int cyclePosition) |
| 18 | 37 | | { |
| 18 | 38 | | var head = ToListNode(array); |
| | 39 | |
|
| 18 | 40 | | if (head == null || cyclePosition < 0) |
| 6 | 41 | | { |
| 6 | 42 | | return head; |
| | 43 | | } |
| | 44 | |
|
| 24 | 45 | | ListNode? lastNode = head, cycleNode = null; |
| | 46 | |
|
| 140 | 47 | | for (var index = 0; lastNode.next != null; index++) |
| 58 | 48 | | { |
| 58 | 49 | | if (index == cyclePosition) |
| 10 | 50 | | { |
| 10 | 51 | | cycleNode = lastNode; |
| 10 | 52 | | } |
| | 53 | |
|
| 58 | 54 | | lastNode = lastNode.next; |
| 58 | 55 | | } |
| | 56 | |
|
| 12 | 57 | | if (cyclePosition == array.Length - 1) |
| 2 | 58 | | { |
| 2 | 59 | | cycleNode = lastNode; |
| 2 | 60 | | } |
| | 61 | |
|
| 12 | 62 | | if (cycleNode != null) |
| 12 | 63 | | { |
| 12 | 64 | | lastNode.next = cycleNode; |
| 12 | 65 | | } |
| | 66 | |
|
| 12 | 67 | | return head; |
| 18 | 68 | | } |
| | 69 | | } |