/**
* Definition for singly-linked list.
* public class ListNode {
* public int val;
* public ListNode next;
* public ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode DetectCycle(ListNode head)
{
if(head == null){
return null;
}
var p = head;
var q = head;
var found = false;
while(p != null && q != null && q.next != null && !found){
var t = q;
p = p.next;
q = q.next.next;
if(ReferenceEquals(p,q)){
found = true;
}
}
if(!found){
return null;
}
// p start from head again
// and q standing where it is
// next time they meet point is where cycle starts from
p = head;
while(!ReferenceEquals(p, q)){
p = p.next;
q = q.next;
}
return q;
}
}LeetCode -- Linked List Cycle II
原文:http://blog.csdn.net/lan_liang/article/details/49962291