回答
分析
最优解法:双指针遍历 A+B 与 B+A
function getIntersectionNode(headA: ListNode | null,headB: ListNode | null): ListNode | null {// 双指针法,A指针遍历A+B,B指针遍历B+Alet pA = headA;let pB = headB;while (pA !== pB) {// 注意遍历A结束有pA=undefined的时候// 这样在遍历到A+B结束时,pA===pB===undefinedpB = pB ? pB.next : headA;pA = pA ? pA.next : headB;}return pA;}
参考资料
- 相交链表 - 力扣(LeetCode)[https://leetcode-cn.com/problems/intersection-of-two-linked-lists/]
