题解 | c++#判断链表中是否有环#
判断链表中是否有环
https://www.nowcoder.com/practice/650474f313294468a4ded3ce0f7898b9
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: bool hasCycle(ListNode *head) { ListNode *fast=new ListNode(66);//双指针 ListNode *slow=new ListNode(66); fast=slow=head; while (fast!=NULL&&fast->next!=NULL) {//next存在,则可以找到next->next,避免next->next越界 fast=fast->next->next;//一个跑得快,一个跑得慢,如果有循环,必定会相遇 slow=slow->next;//fast更快,fast不越界,则slow一定不越界 if(slow==fast){ return true; } } return false; } };