架构师训练营 - 第八周 - 作业
发布于: 2020 年 07 月 29 日
有两个单向链表(链表长度分别为 m,n),这两个单向链表有可能在某个元素合并,如下图所示的这样,也可能不合并。现在给定两个链表的头指针,在不修改链表的情况下,如何快速地判断这两个链表是否合并?如果合并,找到合并的元素,也就是图中的 x 元素。
class Solution { /** * @param ListNode $headA * @param ListNode $headB * @return ListNode */ function getIntersectionNode($headA, $headB) { if($headA == null || $headB == null){ return null; } //先判断是否相交,不相交直接返回 if(!$this->isIntersect($headA, $headB)){ return null; } //若相交再找交叉点:分别遍历,并指向另一链表的头,这样遍历的长度相等 $cura = $headA; $curb = $headB; while($cura || $curb){ if($cura === $curb){ break; } $cura = $cura == null ? $headB : $cura->next; $curb = $curb == null ? $headA : $curb->next; } return $cura; } //判断是否相交 function isIntersect($headA, $headB){ if($headB == null || $headB == null){ return false; } while($headA->next != null){ $headA = $headA->next; } while($headB->next != null){ $headB = $headB->next; } return $headA === $headB; }}
划线
评论
复制
发布于: 2020 年 07 月 29 日 阅读数: 29
Anrika
关注
还未添加个人签名 2018.08.21 加入
还未添加个人简介
评论