- /**
- * 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 *f=head;
- ListNode *s=head;
- while(f!=NULL&&f->next!=NULL){
- s=s->next;
- f=f->next->next;
- if(s==f){
- ListNode *l1=f;
- ListNode *l2=head;
- while(l1!=l2){
- l1=l1->next;
- l2=l2->next;
- }
- return l1;
- }
- }
- return NULL;
- }
- };