-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProblem28.cs
More file actions
36 lines (32 loc) · 1006 Bytes
/
Problem28.cs
File metadata and controls
36 lines (32 loc) · 1006 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
namespace LeetCode;
/// <summary>
/// <see href="https://leetcode.com/problems/linked-list-cycle/">Linked List Cycle</see>.
/// </summary>
public static class Problem28
{
/// <summary>
/// Given head, the head of a linked list, determine if the linked list has a cycle in it.
/// Return true if there is a cycle in the linked list. Otherwise, return false.
/// Time complexity: O(n).
/// Space complexity: O(1).
/// </summary>
/// <param name="head">Linked list's head.</param>
/// <returns>True, if there is a cycle in the linked list.</returns>
public static bool HasCycle(ListNode? head)
{
if (head == null)
{
return false;
}
for (ListNode slow = head, fast = head; fast.Next?.Next != null && slow.Next != null;)
{
slow = slow.Next;
fast = fast.Next.Next;
if (slow == fast)
{
return true;
}
}
return false;
}
}