题解 | #判断链表中是否有环#
判断链表中是否有环
http://www.nowcoder.com/practice/650474f313294468a4ded3ce0f7898b9
哈希方式
class Solution { public: bool hasCycle(ListNode *head) { unordered_map<ListNode *, bool> m; while(head){ if(m.find(head) != m.end()) return true; m[head] = true; head = head->next; } return false; } };
快慢指针
class Solution { public: bool hasCycle(ListNode *head) { //快慢指针 if(!head) return false; ListNode * slow = head; ListNode * fast = head->next; while(slow != fast && slow && fast){ slow = slow->next; fast = fast->next; if(!fast) return false; fast = fast->next; } if(slow == fast) return true; return false; } };