Skip to content

Instantly share code, notes, and snippets.

@jianminchen
Created July 15, 2016 00:12
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/cc0f97525e3eb68db23f4a07ec0b7e90 to your computer and use it in GitHub Desktop.
Save jianminchen/cc0f97525e3eb68db23f4a07ec0b7e90 to your computer and use it in GitHub Desktop.
Linked List Cycle - facebook code lab - wrong answer - still need to figure out, the code is not very efficient.
/**
* 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.
*/
public ListNode detectCycle(ListNode a) {
if(a == null)
return null;
ListNode normalRunner = a;
ListNode doubleRunner = a;
while(normalRunner != null
&& doubleRunner != null
&& normalRunner != doubleRunner)
{
normalRunner = normalRunner.next;
if(doubleRunner.next == null)
return null;
else
doubleRunner = doubleRunner.next.next;
}
//if(normalRunner == null) // bug001
if(normalRunner == null || doubleRunner == null)
return null;
ListNode thirdRunner = a;
while(thirdRunner != null
&& normalRunner != null
&& thirdRunner != normalRunner)
{
thirdRunner = thirdRunner.next;
normalRunner = normalRunner.next;
}
return normalRunner;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment