一种方法是用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 };
View Code

相关文章: