题解 | #判断链表中是否有环#
判断链表中是否有环
http://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) { //cout << head->next->val; //if(head == nullptr) return false; ListNode * fast_ptr = head; ListNode * slow_ptr = head; while(fast_ptr != nullptr && fast_ptr->next != nullptr){ slow_ptr = slow_ptr->next; fast_ptr = fast_ptr->next->next; //判断两个节点是否相同,不直接判断值的原因是可能是空指针 if(slow_ptr == fast_ptr) return true; } return false; } };