题解 | #快慢指针-判断链表中是否有环#
判断链表中是否有环
https://www.nowcoder.com/practice/650474f313294468a4ded3ce0f7898b9
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ /*快慢指针,若有环,必然会再次相遇,否则快指针会跑到NULL*/ class Solution { public: bool hasCycle(ListNode *head) { if(head == nullptr) return false; ListNode *slow = head; ListNode *fast = head; while(fast !=nullptr && fast->next != nullptr){ fast = fast->next->next; //快指针每次跑两步 slow = slow->next;//慢指针每次跑一步 if(slow == fast) return true; } return false; } };