Last active
August 29, 2015 14:01
-
-
Save ericpony/45c14deda5dd85f5e981 to your computer and use it in GitHub Desktop.
Given a linked list, return the node where a cycle begins, or return null if there is no cycle.
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
/** | |
* Definition for singly-linked list. | |
* class ListNode { | |
* int val; | |
* ListNode next; | |
* ListNode(int x) { | |
* val = x; | |
* next = null; | |
* } | |
* } | |
*/ | |
public class Solution | |
{ | |
public ListNode detectCycle(ListNode head) { | |
if(head==null) return null; | |
ListNode slow = head, fast = head; | |
try { | |
do { | |
fast = fast.next; | |
fast = fast.next; | |
slow = slow.next; | |
} while(fast!=null && fast!=slow); | |
} catch(Exception e){} | |
if(slow==null || fast==null || slow!=fast) | |
return null; | |
slow = head; | |
while(slow!=fast) { | |
slow = slow.next; | |
fast = fast.next; | |
} | |
return slow; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment