当前位置: 首页 > >

leetcode 判断链表是否有环

发布时间:

快慢指针,还可以用于查找链表的倒数第几个结点


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 fast = fast->next;
i++;
}
if (fast == nullptr)
return nullptr;
while (fast->next != nullptr){
fast = fast->next;
slow = slow->next;
}
return slow;
}

?



友情链接: