Skip to content

Instantly share code, notes, and snippets.

@jianminchen
Created July 15, 2016 00:18
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 jianminchen/65796a60e7320784231bd1883af0d6f8 to your computer and use it in GitHub Desktop.
Save jianminchen/65796a60e7320784231bd1883af0d6f8 to your computer and use it in GitHub Desktop.
Linked List Cycle - facebook code lab - pass test case - study code: https://siddontang.gitbooks.io/leetcode-solution/content/linked_list/linked_list_cycle.html
/**
* Definition for singly-linked list.
* class ListNode {
* public int val;
* public ListNode next;
* ListNode(int x) { val = x; next = null; }
* }
*/
public class Solution {
/*
1. if there is no cycle, return null
2. if there is a cycle, use two runner, meet a same node;
and then, third runner starts from begining to meet the normal
runner at the beginning of cycle.
study the code:
https://siddontang.gitbooks.io/leetcode-solution/content/linked_list/linked_list_cycle.html
*/
public ListNode detectCycle(ListNode a) {
if(a == null || a.next == null) {
return null;
}
ListNode fast = a;
ListNode slow = a;
while(fast.next != null && fast.next.next != null) {
fast = fast.next.next;
slow = slow.next;
if(fast == slow) {
slow = a;
while(slow != fast) {
fast = fast.next;
slow = slow.next;
}
return slow;
}
}
return null;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment