Created
May 26, 2014 01:47
-
-
Save Cee/5b9a48cb754ef747e350 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 first = head; | |
ListNode second = head; | |
boolean flag = false; | |
while ((second.next != null) && (second.next.next != null)){ | |
first = first.next; | |
second = second.next.next; | |
if (first == second) { | |
flag = true; | |
break; | |
} | |
} | |
if (flag == false) { | |
return null; | |
} else { | |
ListNode circleStart = second; | |
int circleLength = 1; | |
while (second.next != circleStart){ | |
circleLength++; | |
second = second.next; | |
} | |
first = head; | |
do{ | |
second = first; | |
for (int i = 0; i < circleLength; i++){ | |
second = second.next; | |
} | |
if (second == first) break; | |
first = first.next; | |
}while(true); | |
return first; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment