Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yohey03518/4c1c3c2b743d892b1d2e3a601a16d005 to your computer and use it in GitHub Desktop.
Save yohey03518/4c1c3c2b743d892b1d2e3a601a16d005 to your computer and use it in GitHub Desktop.
public bool HasCycle(ListNode head)
{
// case of 0 or 1 node
if (head == null || head.next == null)
return false;
ListNode slowPtr = head;
ListNode fastPtr = head.next;
while (fastPtr != slowPtr && fastPtr.next != slowPtr)
{
// fastPtr走訪到盡頭代表無cycle
if (fastPtr.next == null || fastPtr.next.next == null)
return false;
slowPtr = slowPtr.next;
fastPtr = fastPtr.next.next;
}
return true;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment