题目链接: Linked List Cycle II
题目意思: 给定一个链表,如果链表有环求出环的起点,否则返回NULL
解题思路:
1. 判断链表是否有环: 两个指针,一个一次走一步,一个一次走两步,如果指针相遇说明有环,否则无环。
2. 如果有环的情况下,我们可以画个图(图片来自网络)
假设两个指针在z点相遇。则
a. 指针1走过路程为a + b;指针2走过的路程为 a+b+c+b
b. 因为指针2的速度是指针1的两倍,则有2(a+b) = a+b+c+b => a = c
c. 因此,当两个指针在z点相遇之后,可以让指针1指向链表起点x,然后两个指针每次分别都走一步
当两个指针再次相遇的时候,即为环的起点,即Y点
代码:
/**
* 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* Solution::detectCycle(ListNode *head) {
if (NULL == head) {
return NULL;
}
ListNode *tmpHeadOne = head;
ListNode *tmpHeadTwo = head;
int step = 0;
bool isCycle = false;
while ((tmpHeadOne != NULL) && (tmpHeadTwo != NULL)) {
if ((step != 0) && (tmpHeadOne == tmpHeadTwo)) {
isCycle = true;
break;
}
step++;
tmpHeadOne = tmpHeadOne->next;
tmpHeadTwo = tmpHeadTwo->next;
if (tmpHeadTwo != NULL) {
tmpHeadTwo = tmpHeadTwo->next;
}
}
if (!isCycle) {
return NULL;
}
tmpHeadOne = head;
while (tmpHeadOne != tmpHeadTwo) {
tmpHeadOne = tmpHeadOne->next;
tmpHeadTwo = tmpHeadTwo->next;
}
return tmpHeadOne;
}