首页 > 代码库 > 142. Linked List Cycle II

142. Linked List Cycle II

Given a linked list, return the node where the cycle begins. If there is no cycle, return null.

Note: Do not modify the linked list.

Follow up:
Can you solve it without using extra space?

 

假设head到环的位置距离为a,俩pointer相遇距离环起始位置为b

2(a + b + mCycle) = a + b + nCycle;

=>a+b = (n-m)Cycle

a = (n-m)Cycle - b;

所以一开始俩个pointer相遇位置与head一同往下走,再次相遇的位置即为cycle起始点。

public ListNode DetectCycle(ListNode head) {         if(head == null) return null;         var slow = head;         var fast = head;         while(fast!= null && fast.next != null)         {             slow = slow.next;             fast = fast.next.next;             if(slow == fast) break;         }         if(fast== null || fast.next == null) return null;         slow = head;         while(slow != fast)         {             slow = slow.next;             fast = fast.next;         }         return slow;     }    

 

扩展问题

http://www.cnblogs.com/hiddenfox/p/3408931.html

在网上搜集了一下这个问题相关的一些问题,思路开阔了不少,总结如下:

1. 环的长度是多少?

2. 如何找到环中第一个节点(即Linked List Cycle II)?

3. 如何将有环的链表变成单链表(解除环)?

4. 如何判断两个单链表是否有交点?如何找到第一个相交的节点?

142. Linked List Cycle II