简介
容易想到的方法就是 map , set 之类的.
code
class Solution {
public:
ListNode *detectCycle(ListNode *head) {
if(head == nullptr) return nullptr;
ListNode *p = head;
unordered_map<ListNode*, bool> m;
int index = 0;
while(p){
if(m[p]){
return p;
}
index++;
m[p] = true;
p = p->next;
}
return nullptr;
}
};
public class Solution {
public ListNode detectCycle(ListNode head) {
ListNode p = head;
Map<ListNode, Boolean> m = new HashMap<ListNode, Boolean>();
while(p != null){
if(m.containsKey(p)){
return p;
}
m.put(p, true);
p = p.next;
}
return null;
}
}