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) {
if(head==NULL)return NULL;
//确定第一次相遇点
ListNode* p1=head;
ListNode* p2=head;
while(p2){
//p1向前移动一步
p1=p1->next;
//p2向前移动两步
p2=p2->next;
if(p2) p2=p2->next;
if(p2 && p1==p2) break;
}
//如果没有环
if(p2==NULL)return NULL;
//如果有环
//p2指向链表头
p2=head;
//p1p2都已一步速向前推进,直至相遇
while(p1!=p2){
p1=p1->next;
p2=p2->next;
}
return p1;
}
};LeetCode: Linked List Cycle II [142],布布扣,bubuko.com
LeetCode: Linked List Cycle II [142]
原文地址:http://blog.csdn.net/harryhuang1990/article/details/35780221