题解 | #判断链表中是否有环#
判断链表中是否有环
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) { if(head==nullptr||head->next==nullptr) return false; ListNode* first = head; ListNode* second = head; while(second!=nullptr&&second->next!=nullptr) { first=first->next; second=second->next->next; if(first == second)//比较的是链接的地址相等,而不是链接的值相等 return true; } return false; } };
第一:注意head为nullptr或者head为一个链接的情况
第二:比较的是链接的地址相等,而不是链接的值相等
第三:second!=nullptr&&second->next!=nullptr,不光注意second当前有无,还要下一个,因为移动二次
#链表#