快慢指针,还可以用于查找链表的倒数第几个结点
bool hasCycle(ListNode *head) {
if(head == nullptr)
return false;
ListNode * pAhead = head;
ListNode * pBehind = head;
while(pBehind != nullptr && pBehind->next!= nullptr){//注意循环退出的条件为快指针不为空
pAhead = pAhead->next;
pBehind =pBehind->next->next;
if(pAhead == pBehind){
return true;
}
}
return false;
}
ListNode* FindlistNode(ListNode* head, int n)
{
if (head == nullptr)
return head;
ListNode * slow = head;
ListNode* fast = head;
int i = 1;
while (fast != nullptr && i<n){
fast = fast->next;
i++;
}
if (fast == nullptr)
return nullptr;
while (fast->next != nullptr){
fast = fast->next;
slow = slow->next;
}
return slow;
}