题意:
判断给定的链表中是否有环。如果有环则返回true,否则返回false。
方法:
快慢指针
思路:快慢指针。
快慢指针从同一起点出发,慢指针速度为1,快指针速度为2。如果快慢指针相遇,则说明有环;否则,因为快指针速度快,所以会最先遇到 null 而退出循环,说明无环。
class Solution {
public:
bool hasCycle(ListNode *head) {
if(head==nullptr)
return false;
ListNode *p=head,*q=head;//快慢指针
while(q){
p=p->next;//慢指针速度为1
if(q->next)//快指针速度为2
q=q->next->next;
else
return false;
if(p==q)//如果快慢指针相遇,则说明有环
return true;
}
return false;
}
};
时间复杂度:
空间复杂度:![]()



京公网安备 11010502036488号