1. Topic
Given a list loop, the algorithm returns to realize a loop at the beginning of the node.
A cycloalkyl list definition: the next element in the list point to a node in the node preceding it had occurred, it indicates the presence of the chain loop.
示例 1:
输入:head = [3,2,0,-4], pos = 1
输出:tail connects to node index 1
解释:链表中有一个环,其尾部连接到第二个节点。
示例 2:
输入:head = [1,2], pos = 0
输出:tail connects to node index 0
解释:链表中有一个环,其尾部连接到第一个节点。
示例 3:
输入:head = [1], pos = -1
输出:no cycle
解释:链表中没有环。
进阶:
你是否可以不用额外空间解决此题?
Source: stay button (LeetCode)
link: https: //leetcode-cn.com/problems/linked-list-cycle-lcci
copyrighted by deduction from all networks. Commercial reprint please contact the authorized official, non-commercial reprint please indicate the source.
2. Problem Solving
- Pointer speed, fast take two steps, slow step, when
fast==slow
the presence of a ring - Then slow pointer back to square one, only one speed all go one step further, meet again point is the entrance to the ring
- DETAILED derivation, see: the list loop detection
class Solution {
public:
ListNode *detectCycle(ListNode *head) {
ListNode *fast = head, *slow = head;
while(fast && fast->next)
{
fast = fast->next->next;
slow = slow->next;
if(fast == slow)
break;
}
if(!fast || !fast->next)
return NULL;
slow = head;
while(fast != slow)
{
fast = fast->next;
slow = slow->next;
}
return fast;
}
};