Thursday, April 28, 2022

[LeetCode] 141. Linked List Cycle

    

"踏上LeetCode解題之路,順手紀錄一下PHP練功的過程囉。這是第十四篇~~"


Linked List Cycle - LeetCode


思考過程

待補上


結果⚠️

/**
 * 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) {
        
        if ($head === null){            
            return false;
    }
        
        $set = [];
        while ($head !== null) {
            
            if (in_array($head, $set)) {
                return true;
            }
            
            $set[] = $head;
            $head = $head->next;
            
        }
        
        return false;
}
    
}

Contact Form

Name

Email *

Message *