| | 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.LinkedListCycle; |
| | 15 | |
|
| | 16 | | /// <inheritdoc /> |
| | 17 | | public class LinkedListCycleTwoPointers : ILinkedListCycle |
| | 18 | | { |
| | 19 | | /// <summary> |
| | 20 | | /// Time complexity - O(n) |
| | 21 | | /// Space complexity - O(1) |
| | 22 | | /// </summary> |
| | 23 | | /// <param name="head"></param> |
| | 24 | | /// <returns></returns> |
| | 25 | | public bool HasCycle(ListNode? head) |
| 9 | 26 | | { |
| 9 | 27 | | if (head == null) |
| 1 | 28 | | { |
| 1 | 29 | | return false; |
| | 30 | | } |
| | 31 | |
|
| 8 | 32 | | var slow = head; |
| 8 | 33 | | var fast = head.next; |
| | 34 | |
|
| 36 | 35 | | while (fast is { next: not null }) |
| 34 | 36 | | { |
| 34 | 37 | | if (slow == fast) |
| 6 | 38 | | { |
| 6 | 39 | | return true; |
| | 40 | | } |
| | 41 | |
|
| 28 | 42 | | slow = slow?.next; |
| 28 | 43 | | fast = fast.next.next; |
| 28 | 44 | | } |
| | 45 | |
|
| 2 | 46 | | return false; |
| 9 | 47 | | } |
| | 48 | | } |