简介
思路
因为C++可以存储地址, 直接判断地址是否被访问过即可.
code
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
bool hasCycle(ListNode *h) {
map<struct ListNode *, bool> m;
bool check = false;
while(h){
if(m[h] == true){
check = true;
break;
}else{
m[h] = true;
}
h = h->next;
}
return check;
}
};
public class Solution {
public boolean hasCycle(ListNode head) {
Set<ListNode> seen = new HashSet<ListNode>();
while(head != null){
if(!seen.add(head)){ // 如果已经存在了这个东西, add 会返回false.
return true;
}
head = head.next;
}
return false;
}
}