环形链表求入环节点
public class Solution {
public ListNode detectCycle(ListNode head) {
if (head == null) {
return null;
}
ListNode slow = head;
ListNode fast = head;
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
if (slow == fast) {
ListNode ans = head;
while (slow != ans) {
slow = slow.next;
ans = ans.next;
}
return ans;
}
}
return null;
}
}
快慢指针,先定位到快慢指针重复节点,再新建答案节点指向头部,和慢指针一次一步,直到相遇。