Original link: leetcode-cn.com/problems/li…

Answer:

The two started at the same time, the slow one taking one step at a time, the fast two. If there is a ring, the two must meet. If it does not exist, the fast man will certainly have no way out first.

/** * @param {ListNode} head * @return {Boolean} */ var hasCycle = function (head) { We must ensure that both head and head.next exist if (! head || ! head.next) { return false; } // let slow = head; let fast = head.next; // If the fast and slow Pointers do not meet, proceed while (slow! If (! = 0) {// If (! = 0) {if (! = 0) { fast.next || ! fast.next.next) { return false; } // Slow = slow. Next; fast = fast.next.next; } return true; };Copy the code
/** * @param {ListNode} head * @return {boolean} */ var hasCycle = function (head) { if (! head || ! head.next) { return false; } let slow = head; let fast = head; while (fast && fast.next) { slow = slow.next; fast = fast.next.next; if (slow === fast) { return true; } } return false; };Copy the code

Optimized code:

/** * @param {ListNode} head * @return {boolean} */ var hasCycle = function (head) { let slow = head; // let fast = head; // If the fast pointer can still be moved, continue traversing the list. While (fast && fast.next && fast.next-next) {slow = slow. Next; fast = fast.next.next; If (slow === fast) {return true; } } return false; };Copy the code