141 Linked List Cycle ✅¶
::: tip Key points 💡
- Run slow and fast pointer :::
Given head, the head of a linked list, determine if the linked list has a cycle in it.
There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the next pointer. Internally, pos is used to denote the index of the node that tail's next pointer is connected to. Note that pos is not passed as a parameter.
Return true if there is a cycle in the linked list. Otherwise, return false.
Example 1:
Input: head = [3,2,0,-4], pos = 1
Output: true
Explanation: There is a cycle in the linked list, where the tail connects to the 1st node (0-indexed).
Example 2:
Input: head = [1,2], pos = 0
Output: true
Explanation: There is a cycle in the linked list, where the tail connects to the 0th node.
Example 3:
C# Solution¶
Time complexity: O(n) Space complexity: O(1)
using System;
namespace Algorithms.Simple
{
public class ListNode
{
public int val;
public ListNode next;
public ListNode(int x)
{
val = x;
}
}
public class LinkedListCycle
{
public static bool HasCycle(ListNode head)
{
if (head == null || head.next == null) return false;
ListNode slow = head;
ListNode fast = head.next;
while (slow != fast)
{
if (head == null || head.next == null) return false;
slow = slow.next;
fast = fast.next.next;
}
return true;
}
}
}
C# Tests¶
using Algorithms.Simple;
using Xunit;
namespace AlgorithmTests.Simple
{
public class LinkedListCycleTests
{
[Fact]
public void HasCycleTestTrue1()
{
var nodeList = new ListNode[4];
var node1 = new ListNode(3);
var node2 = new ListNode(2);
var node3 = new ListNode(0);
var node4 = new ListNode(-4);
node1.next = node2;
node2.next = node3;
node3.next = node4;
node4.next = node2;
Assert.True(LinkedListCycle.HasCycle(node1));
}
[Fact]
public void HasCycleTestTrue2()
{
var nodeList = new ListNode[2];
var node1 = new ListNode(1);
var node2 = new ListNode(2);
node1.next = node2;
node2.next = node1;
Assert.True(LinkedListCycle.HasCycle(node1));
}
[Fact]
public void HasCycleTestFalse()
{
var nodeList = new ListNode[1];
var node1 = new ListNode(1);
Assert.False(LinkedListCycle.HasCycle(node1));
}
}
}
Solution1: HashTable¶
Time complexity: O(n) Space complexity: O(n)