Skip to content

Instantly share code, notes, and snippets.

@Cee
Created May 26, 2014 01:47
Show Gist options
  • Save Cee/5b9a48cb754ef747e350 to your computer and use it in GitHub Desktop.
Save Cee/5b9a48cb754ef747e350 to your computer and use it in GitHub Desktop.
/**
* 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