160. Intersection of Two Linked Lists

計算兩條路的交叉點,上路加下路,使兩路步數相同,這樣在第二圈的時候就會同時碰到交叉點。要特別注意是比較指針,而非比較值。

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

class Solution {
    /**
     * @param ListNode $headA
     * @param ListNode $headB
     * @return ListNode
     */
    function getIntersectionNode($headA, $headB) {
        if (!$headA || !$headB) {
            return null;
        }

        $a = $headA;
        $b = $headB;
        while($a !== $b) {
            if ($a->next == null && $b->next == null) {
                return null;
            }

            $a = $a->next ?: $headB;
            $b = $b->next ?: $headA;
        }

        return $b;
    }
}

Last updated