快慢指针(总会追上的)
判断链表中是否有环
http://www.nowcoder.com/questionTerminal/650474f313294468a4ded3ce0f7898b9
class Solution {
public:
bool hasCycle(ListNode *head) {
if (head == nullptr || head->next == nullptr)
return false;
ListNode * slow = head, * fast = head->next;
while (fast != nullptr && fast->next != nullptr)
{
if (fast == slow)
return true;
slow = slow->next;
fast = fast->next->next;
}
return false;
}
};