一种方法是用set存储出现过的指针,重复出现时就是有环:
1 class Solution { 2 public: 3 bool hasCycle(ListNode *head) { 4 set<ListNode*> st; 5 ListNode *p = head; 6 while(p) { 7 if (st.find(p) != st.end()) 8 return true; 9 st.insert(p); 10 p = p->next; 11 } 12 return false; 13 } 14 };
另一种方法就是快慢指针,快指针一次走两步,慢指针一次走一步。无环时快指针会走向空指针,有环时快指针会赶上慢指针。
1 class Solution { 2 public: 3 bool hasCycle(ListNode *head) { 4 ListNode *fast, *slow; 5 fast = slow = head; 6 while (fast && fast->next) { 7 slow = slow->next; 8 fast = fast->next->next; 9 if (fast == slow) 10 return true; 11 } 12 return false; 13 } 14 };