您的位置:首页 > 其它

【leetcode】Linked List Cycle II

2015-05-04 19:36 190 查看

Linked List Cycle II

Given a linked list, return the node where the cycle begins. If there is no cycle, return null.

Follow up:

Can you solve it without using extra space?

思路:

用双指针的方案,一个指针每次走一步,另一个走两步,如果有相等的点,那么就是有环。但是注意返回的时候,要返回环的开始,因此要重新循环一遍。

/**
* 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 *fast,*slow,*result;
if(head==NULL) return NULL;
result=head;
slow=head;
fast=head;
while(1)
{
fast=fast->next;
if(fast==NULL) return NULL;
fast=fast->next;
if(fast==NULL) return NULL;
slow=slow->next;
if(fast==slow) break;
}

while(1)
{
if(fast==result) return result;
fast=fast->next;
result=result->next;
}
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: