判断链表是否有环。
思路就是用快慢指针,慢的每次走一步,快的每次走两步,如果有环,则快慢指针必定相交。
需要注意的是,快指针走两步是,需要确定下一步是否为空。
bool hasCycle(ListNode *head) {if (head == nullptr || head->next== nullptr)return false;ListNode *slow = head;ListNode *fast = head->next->next;while(fast) {if (slow == fast)return true;slow = slow->next;if (fast->next == nullptr)return false;fast = fast->next->next;}return false;}
