题目:
Given a linked list, determine if it has a cycle in it.
Given a linked list, return the node where the cycle begins. If there is no cycle, returnnull.
思路:
链表有环判断:
设置快慢指针,如果快慢指针相遇,则证明有环。
(1)设置快慢指针,因为链表中有环,所以最终会相遇,相遇点为C
(2)两个指针分别放在链表起点和相遇点,以相同的速度前进,最终相遇在环的入口点。
证明:
dAB = a,dBC = b,dCB = c;
2*(a+b) = a + b + n*(b+c);
a = (n - 1) * b + n * c = (n - 1)(b + c) +c;
由此可得出,两个指针放在链表起点和相遇点时,当一个指针走完a距离,另一个指针刚好将环绕了(n-1)圈加上c的距离。
代码:
判断有环:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
bool hasCycle(ListNode *head) {
if(head == NULL) return false;
ListNode *slow = head;
ListNode *quick = head;
while(quick->next != NULL && quick->next->next != NULL){
slow = slow->next;
quick = quick->next->next;
if(slow == quick){
return true;
}
}
return false;
}
};
寻找环的入口点:
class Solution {
public:
ListNode *detectCycle(ListNode *head) {
if(head == NULL) return NULL;
ListNode *h = head;
ListNode *slow = head;
ListNode *quick = head;
while(quick->next != NULL && quick->next->next != NULL){
slow = slow->next;
quick = quick->next->next;
if(slow == quick){
while(quick != h){
quick = quick->next;
h = h->next;
}
return h;
}
}
return NULL;
}
};