交叉連結串列求交點(關鍵詞:連結串列/交叉連結串列/交點/交集)
阿新 • • 發佈:2018-12-12
交叉連結串列求交點
實現
def getIntersectionNode(self, headA, headB): """ :type head1, head1: ListNode :rtype: ListNode """ if headA is not None and headB is not None: pa, pb = headA, headB while pa is not pb: pa = pa.next if pa is not None else headB pb = pb.next if pb is not None else headA return pa
關於程式碼的一點解釋
pa、pb 2 個指標的初始位置是 headA、headB 頭結點,pa、pb 兩個指標一直往後遍歷。
直到 pa 指標走到連結串列的末尾,然後 pa 指向 headB;
直到 pb 指標走到連結串列的末尾,然後 pb 指向 headA;
然後 pa、pb 再繼續遍歷;
每次 pa、pb 指向 None,則將 pa、pb 分別指向 headB、headA。
迴圈的次數越多,pa、pb 的距離越接近,直到 pa 等於 pb。
參考文獻
- 160. Intersection of Two Linked Lists - LeetCode;
- https://leetcode.com/problems/intersection-of-two-linked-lists/discuss/49846/Python-solution-for-intersection-of-two-singly-linked-lists;
- https://leetcode.com/problems/intersection-of-two-linked-lists/discuss/49798/Concise-python-code-with-comments;
- https://leetcode.com/submissions/detail/194298767/。