LeetCode热题100-相交链表
判断相交链表直接想到的方法就是遍历两条链表暴力匹配的方式。时间复杂度n2。class Solution: def getIntersectionNode(self, headA: ListNode, headB: ListNode) - Optional[ListNode]: res ListNode(0) if not headA or not headB: return res curA headA curB headB while curA: while curB: if curA curB: return curA curB curB.next curB headB curA curA.next双指针方法通过统计发现如果存在相交同时遍历A、B链表到公共节点时相等的长度。先遍历A遍历结果为(a-c) c (b-c) a b -c先遍历B遍历结果为(b -c) c (a -c) b a -c所以若存在相交遍历长度一致相交于公共节点若不相交正好为null。class Solution: def getIntersectionNode(self, headA: ListNode, headB: ListNode) - Optional[ListNode]: A headA B headB while A ! B: A A.next if A else headB B B.next if B else headA return A