寻找链表中环的起点
计算链表中环的结点个数
/**
* 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) {
ListNode slow = head, fast = head;
while(fast != null){
if(fast.next == null)
return null;
slow = slow.next;
fast = fast.next.next;
//slow还没有走完一圈快慢指针必定会相遇
if(fast == slow){
ListNode now = head;
//从相遇的地方再次循环
while(now != slow){
slow = slow.next;
now = now.next;
}
return now;
}
}
return null;
}
}
原文:https://www.cnblogs.com/GarrettWale/p/14483240.html