給定兩個 linkedlist ,找到他們的交集處
這題只要用兩個 pointer,走訪完兩個 list 就可以找到交集處
交集處為第一個位置相同的 node
如果沒有交集的話,則會同時走到 null
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> Optional[ListNode]:
pA = headA
pB = headB
while pA!=pB:
pA = pA.next if pA else headB
pB = pB.next if pB else headA
return pA