最经典的双指针题目,解题思路:
(1)先判断头指针head和head->next是否为空,为空则直接返回false
(2)设置两个指针slow、fast,起始都指向head
(3)slow一次向后走1步,fast一次向后走两步
(4)若二者相遇,则有环返回true;若fast->next || fast->next->next为空,则无环返回false
class Solution {
public:
bool hasCycle(ListNode *head) {
if(head == nullptr || head->next == nullptr)
{
return false;
}
ListNode *slow = head, *fast = head;
while(fast->next != nullptr && fast->next->next != nullptr)
{
slow = slow->next;
fast = fast->next->next;
if(slow == fast)
{
return true;
}
}
return false;
}
};