Linked List Cycle I 问题采用删除部分node的方式,缩短圈的大小,但是此题不允许修改原始链表。固放弃了这种方式。该题目采用了一种脑筋急转弯的方式,求解这种问题,amazing。主要借鉴了discuss。有两个人,一个人走一步,一个人走两步,最后得到圈的起始位置。
/**
* 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) {
if(head==NULL)
return NULL;
ListNode *first=head;
ListNode *second=head;
ListNode *cross=NULL;
while(first!=NULL&&second!=NULL&&second->next!=NULL)
{
first=first->next;
second=second->next->next;
if(first==second)
{
cross=first;
break;
}
}
if(cross==NULL)
return NULL;
else
{
first=head;
while(first!=cross)
{
first=first->next;
cross=cross->next;
}
return first;
}
}
};