简介
思路
因为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;
}
}
---------------------------我的天空里没有太阳,总是黑夜,但并不暗,因为有东西代替了太阳。虽然没有太阳那么明亮,但对我来说已经足够。凭借着这份光,我便能把黑夜当成白天。我从来就没有太阳,所以不怕失去。
--------《白夜行》
浙公网安备 33010602011771号