/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
bool hasCycle(ListNode *head) {
if(head == NULL || head->next == NULL)
return false;
ListNode* p_ahead = head;
ListNode* p_behind = head;
while(p_ahead && p_ahead->next){
p_ahead = p_ahead->next->next;
p_behind = p_behind->next;
if(p_ahead == p_behind){
return true;
}
}
return false;
}
};
千万不要再while判断里面加上p->next->next这种连续两次next的判断,一次只想对判断next一次