142. 环形链表 II
/**
* 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) {
ListNode* slow = head;
ListNode* fast = head;
//多创建了一个用于存放相遇位置的节点
ListNode* meet = NULL;
while(fast)
{
slow = slow->next;
fast = fast->next;
if(!fast) return NULL;
fast = fast->next;
if(fast == slow)
{
meet = fast;
//找到相遇节点一定要结束循环
break;
}
}
//如果循环结束后,meet指针仍然为NULL,则没有环
if(meet != NULL)
{
//这里就是同时从链表的头部和相遇节点触发,入环节点到链表头部和相遇节点的长度相同
while(head && meet)
{
if(head == meet)
{
return head;
}
head = head->next;
meet = meet->next;
}
}
return NULL;
}
};
/**
* 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) {
ListNode *slow = head, *fast = head;
do
{
if(!fast || ! fast->next) return NULL;
fast = fast->next->next;
slow = slow->next;
}while(fast != slow);
fast = head;
while(fast != slow)
{
if(fast == slow) break;
fast = fast->next;
slow = slow->next;
}
return fast;
}
};