转载请注明:
原题如下:
题目解析:
这道题目是“判断单链表是否有环,如果有环,求入环点,如果没有返回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* result = NULL;
if(head == NULL || head->next == NULL){
return result;
}
ListNode* slow = head;
ListNode* fast = head;
while(fast != NULL && fast->next != NULL){
slow = slow->next;
fast = fast->next->next;
if(slow == fast){
break;
}
}
//no cycle
if(fast == NULL || fast->next == NULL){
return result;
}
//exist cycle
//the distance is equal from the intersection and head to
//cycle begins.
slow = head;
while(slow != fast){
slow = slow->next;
fast = fast->next;
}
result = slow;
return result;
}
};