bool hasCycle(ListNode *head) { unordered_set<ListNode*> temp; while(head != nullptr){ if(temp.count(head)){ return true; } else[ temp.insert(head); head = head -> next; ] } return false; }
又称龟兔赛跑算法,用快慢指针遍历整个数组,如果指针碰撞,则说明有环,如果都遍历到了空指针,说明没有环路
代码
bool hasCycle(ListNode* head){ if (head == nullptr || head->next == nullptr) { return false; } ListNode* slow = head; ListNode* fast = head -> next; while(slow != fast){ if(fast == nullptr || fast -> next == nullptr) return false; slow = slow -> next; fast = fast -> next -> next; } return true; }