题目链接:https://leetcode.com/problems/intersection-of-two-linked-lists/submissions/
代码
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def getIntersectionNode(self, headA, headB):
"""
:type head1, head1: ListNode
:rtype: ListNode
"""
if not headA or not headB:return None
cur_a,cur_b=headA,headB
while cur_a or cur_b:
if not cur_a:cur_a=headB
if not cur_b:cur_b=headA
if cur_a is cur_b :
return cur_a
cur_a=cur_a.next
cur_b=cur_b.next
思路详解
走完之后从另一个链表头开始走,当相遇的时候,就是在相交节点,路径长度相同