编写一个程序,找到两个单链表相交的起始节点。
    如下面的两个链表:
    image.png
    在节点 c1 开始相交。

    示例 1:
    image.png
    输入:intersectVal = 8, listA = [4,1,8,4,5], listB = [5,0,1,8,4,5], skipA = 2, skipB = 3
    输出:Reference of the node with value = 8
    输入解释:相交节点的值为 8 (注意,如果两个链表相交则不能为 0)。从各自的表头开始算起,链表 A 为 [4,1,8,4,5],链表 B 为 [5,0,1,8,4,5]。在 A 中,相交节点前有 2 个节点;在 B 中,相交节点前有 3 个节点。

    思路:1、先是否相交 2、链接一起遍历,从而获取相交节点

    1. <?php
    2. /**
    3. * @param ListNode $headA
    4. * @param ListNode $headB
    5. * @return ListNode
    6. */
    7. function getIntersectionNode($headA, $headB) {
    8. if($headA == null || $headB == null){
    9. return null;
    10. }
    11. //先判断是否相交,不相交直接返回
    12. if(!$this->isIntersect($headA, $headB)){
    13. return null;
    14. }
    15. //若相交再找交叉点:分别遍历,并指向另一链表的头,这样遍历的长度相等
    16. $cura = $headA;
    17. $curb = $headB;
    18. while($cura || $curb){
    19. if($cura === $curb){
    20. break;
    21. }
    22. $cura = $cura == null ? $headB : $cura->next;
    23. $curb = $curb == null ? $headA : $curb->next;
    24. }
    25. return $cura;
    26. }
    27. //判断是否相交
    28. function isIntersect($headA, $headB){
    29. if($headB == null || $headB == null){
    30. return false;
    31. }
    32. while($headA->next != null){
    33. $headA = $headA->next;
    34. }
    35. while($headB->next != null){
    36. $headB = $headB->next;
    37. }
    38. return $headA === $headB;
    39. }

    ```