题目描述:给定一个链表,返回链表开始入环的第一个节点。 如果链表无环,则返回 null。
法一: 快慢指针
public ListNode detectCycle(ListNode head) {
if (head == null) return null;
ListNode fast = head;
ListNode slow = head;
while (fast != null && fast.next != null) {
fast = fast.next.next;
slow = slow.next;
if (fast == slow)
break;
}
// 遍历完后 fast到达链表末尾,说明无环
if (fast == null || fast.next == null) return null;
// 重置一个指针,重新遍历
slow = head;
// slow从头遍历链表,fast在环中遍历,直到他两相等时就是环的开始位置
while (slow != fast) {
slow = slow.next;
fast = fast.next;
}
return slow;
}