图解
javascript
/**
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/
/**
* @param {ListNode} head
* @return {boolean}
*/
var hasCycle = function (head) {
/**
* 哈希
*/
var map = new Map();
while(head){
if(map.has(head)) return true
map.set(head,head.val)
head = head.next;
}
return false;
/**
* 快慢指针
*/
var p1 = head,p2 = head;
while(p2 && p2.next){
p1 = p1.next;
p2 = p2.next.next;
if(p1 == p2) return true
}
return false;
};
C++
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
bool hasCycle(ListNode *head) {
if(head == NULL) return false;
ListNode *p = head,*q = head->next;
while(q!=p && q && q->next){
p = p->next;
q = q->next->next;
}
return p == q;
}
};