题目:链表中环的入口节点
思路:
不考虑空间,可以用一个集合来做。
考虑空间:若有环,快慢指针必定会相遇。如下图:
A是链表起始节点,B是环的入口,C是快慢指针相交的位置。
相遇时:快指针走过:a + b + c + b;慢指针走过:a + b。
由于快指针每次移动2步,因此,相遇时,快指针走的路程是慢指针的2倍。所以,有:
a + b + c + b = 2 * (a + b),即a = c。
相遇后,把slow指向head,slow和fast同步移动,再次相遇就是入口节点。
代码:
/**
* 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 || head.next == 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) {
slow = head;
while (slow != fast) {
slow = slow.next;
fast = fast.next;
}
return slow;
}
}
return null;
}
}