给定一个链表,判断链表中是否有环。
主要是运用快慢指针
直接贴c++代码:
bool hasCycle(ListNode *head) {
if (head == NULL || head->next == NULL)
return false;
//快慢指针
ListNode *fast = head->next;
ListNode *slow = head;
//快慢指针相遇则存在环
while (fast != slow){
if (fast->next == NULL || fast->next->next == NULL)
return false;
//快指针每次走2
fast = fast->next->next;
//慢指针每次走1
slow = slow->next;
}
return true;
}