LeetCode-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) { // IMPORTANT: Please reset any member data you declared, as // the same Solution instance will be reused for each test case. ListNode * p1=head,*p2=head; ListNode * pic,*ptr; if(head==NULL)return NULL; int length=1;//length of the circle while(true){ p1=p1->next; if(p1==NULL)return NULL; p2=p2->next; if(p2==NULL)return NULL; p2=p2->next; if(p2==NULL)return NULL; if(p1==p2){ pic=p1; ptr=p2; break; } } while(ptr->next!=pic){ length++; ptr=ptr->next; } if(length==1)return pic; p1=head; for(int i=0;i<length;i++){ p1=p1->next; } p2=head; while(p1!=p2){ p1=p1->next; p2=p2->next; } return p1; } };