题目:
https://leetcode-cn.com/problems/linked-list-cycle-ii/submissions/
代码:
/**
-
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 *p1 = head;
ListNode *p2 = head;
int pos = 0;
bool has = false;while(true) { while(p1!=NULL&&p2!=NULL&&p1!=p2) { if(p2->next==NULL) { return NULL; } else { p2 = p2->next->next; } p1 = p1->next; pos++; } if(p1==NULL||p2 == NULL) { return NULL; } if(p1 == p2&&pos!=0) { ListNode *p3 = head; while(p3!=p1) { p3 = p3->next; p1 = p1->next; } return p3; } if(p1 == p2&&pos ==0) { p1 = p1->next; if(p2->next == NULL) { return NULL; } else { p2 = p2->next->next; } pos++; } }
}
};