141. Linked List Cycle

建立一個跑更快的指針去追較慢的指針,如果走到底沒遇到,就表示沒循環

/**
 * Definition for a singly-linked list.
 * class ListNode {
 *     public $val = 0;
 *     public $next = null;
 *     function __construct($val) { $this->val = $val; }
 * }
 */

class Solution {
    /**
     * @param ListNode $head
     * @return Boolean
     */
    function hasCycle($head) {
        $fast = $head;
        while($fast && $fast->next) {
            $head = $head->next;
            $fast = $fast->next->next;
            if ($head === $fast) {
                return true;
            }
        }
    
        return false;
    }
}

Last updated