Created
August 28, 2018 14:51
-
-
Save yohey03518/4c1c3c2b743d892b1d2e3a601a16d005 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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