剑指 Offer II 022. 链表中环的入口节点

其实本题的难点在于如果数学推导。
环的入口点.png

  1. public class Solution {
  2. public ListNode detectCycle(ListNode head) {
  3. // 入口节点
  4. if (head == null) return null;
  5. ListNode fast = head, slow = head;
  6. while (fast != null && fast.next != null) {
  7. fast = fast.next.next;
  8. slow = slow.next;
  9. // 环中相遇
  10. if (fast == slow) {
  11. fast = head;
  12. while (fast != slow) {
  13. fast = fast.next;
  14. slow = slow.next;
  15. }
  16. return fast;
  17. }
  18. }
  19. return null;
  20. }
  21. }