快慢指针 js

 * function ListNode(x){
 *   this.val = x;
 *   this.next = null;
 * }
 */

/**
 * 
 * @param head ListNode类 
 * @return bool布尔型
 */
function hasCycle( head ) {
    // write code here
    let p = head,q = head
    while(p && p.next){
        p = p.next.next
        q = q.next
        if(p === q){
            return true
        }
    }
    return false
}
module.exports = {
    hasCycle : hasCycle
};

alt

c

 * struct ListNode {
 *	int val;
 *	struct ListNode *next;
 * };
 */

/**
 * 
 * @param head ListNode类 
 * @return bool布尔型
 */
bool hasCycle(struct ListNode* head ) {
    // write code here
    struct ListNode* p = head;
    struct ListNode* q = head;
    while(p != NULL && p -> next != NULL){
        p = p -> next -> next;
        q = q -> next;
        if(p == q)    return true;
    }
    return false;
}

alt

java

 * Definition for singly-linked list.
 * class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    public boolean hasCycle(ListNode head) {
        ListNode p = head;
        ListNode q = head;
        while(p!=null && p.next!=null){
            p = p.next.next;
            q = q.next;
            if(p==q){
                return true;
            }
        }
        return false;
    }
}

alt