一. 问题: 求链表是否有环及环的入口
二. leetcode 题目:
142. Linked List Cycle II
https://leetcode.com/problems/linked-list-cycle-ii/
Given a linked list, return the node where the cycle begins. If there is no cycle, return null
.
To represent a cycle in the given linked list, we use an integer pos
which represents the position (0-indexed) in the linked list where tail connects to. If pos
is -1
, then there is no cycle in the linked list.
SourceCode
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *detectCycle(ListNode *head) {
if (head == NULL) return NULL;
ListNode* first = head;
ListNode* second = head;
bool isCycle = false;
while (first && second) {
first = first->next;
if (second->next == NULL) return NULL;
second = second->next->next;
if (first == second) { isCycle = true; break; }
}
if (!isCycle) return NULL;
first = head;
while (first != second) {
first = first->next;
second = second->next;
}
return first;
}
};
三:证明:入环点算法的正确性
即:设置两个指针,分别从起始点和相交点(meetPostion)出发,每次迭代一步,当两个指针相等时,就是入环点
1) 首先假设兔子每次迭代走两步,乌龟每次走一步。那么,当乌龟走到入环点时,兔子正好处于环上的绿色位置HarePos,此时可以得出一下两个结论a 和 b:
a. 兔子所走的距离时乌龟的两倍
即:2m = m + i + xn
即: m = i + xn
b. 此时,兔子开始在环上开始追乌龟,他们之间的相对距离为n - i,而每迭代一次,兔子和乌龟的相对距离减一,即经过n-i 此迭代后,兔子可以在紫色位置meetPostion追上乌龟,而迭代 n-i 次正好就是乌龟走的距离,即从入环点到相遇点的距离就是 n - i, 那么, 从相遇点再到入环点的距离就是 i' = n - (n -i) = i
2 ) 假设两只乌龟t1,t2,t1从起始位置开始走,t2从相遇点走,
那么有t1走到入环点的距离是: m,结论a有 m = i + xn. 即t1走了 i + xn步, 而t2 也是走了 i + xn, 更据结论b, 此时t2 也必然走到入环点。即经过i + xn步,t1,t2相遇在入环点。