Skip to content

Instantly share code, notes, and snippets.

@ericpony
Last active August 29, 2015 14:01
Show Gist options
  • Save ericpony/45c14deda5dd85f5e981 to your computer and use it in GitHub Desktop.
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.
/**
* 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