题目地址:https://oj.leetcode.com/problems/linked-list-cycle-ii/
解题思路:快慢指针,相遇后快指针回到起点以每次一步走,再次相遇点为环的起点
注意【纯回环】,空链表,无环链表等各种情况
/**
* 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 fast=head;
ListNode low=head;
ListNode second=head;
boolean hasCycle=false;
while(fast!=null&&low!=null){
if(fast.next!=null)fast=fast.next.next;
else {
break;
}
low=low.next;
if(fast==low){
hasCycle=true;
break;
}
}
if(!hasCycle) return null;
else{
while(second!=low){
second=second.next;
low=low.next;
}
return low;
}
}
}