Created
July 15, 2016 00:12
-
-
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.
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 { | |
* 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