快慢指针
为什么相遇后让快指针回到起点,再让快指针和慢指针都一步一步地走,它们就会在环的入口相遇?
复杂度
- 时间复杂度: O(n)
- 空间复杂度: O(1)
public ListNode detectCycle(ListNode head) {
ListNode slow = head, fast =head;
ListNode result = null;
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
if (fast == slow) {
break;
}
}
fast = head;
while (slow != null && slow.next != null) {
if (fast == slow){
result = fast;
break;
}
slow = slow.next;
fast = fast.next;
}
return result;
}