#160. 相交链表

题目:

 思路:我这个方法比较简单,就是先计算链表A和链表B长度,长度大的先走差值步数,然后两个链表一起走,到了公共节点,就找到了。

代码:

# 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) -> ListNode:
        a1 = headA
        a2 =headB
        n1=0
        n2=0
        while a1:
            n1=n1+1
            a1=a1.next
        while a2:
            n2=n2+1
            a2=a2.next
        if(n1>n2):
            for i in range(1,n1-n2+1):
                headA=headA.next
        else:
            for i in range(1,n2-n1+1):
                headB=headB.next
        while(headA!=headB):
            headA=headA.next
            headB=headB.next
        return headA
原文地址:https://www.cnblogs.com/wangyufeiaichiyu/p/14790977.html