第四十二天 Intersection of Two Linked Lists

今天尽管比较晚,但还是坚持开始刷

前两周断的比较多,先稳定一下,把这一周先坚持下来,先保持每周一题的节奏

https://leetcode-cn.com/problems/intersection-of-two-linked-lists/description/

今天这道是看两个链表是否相交,题意理解不难,这次就是用的一个相对比较“直接的思路”:
1、分别获取两个链表的长度
2、在遍历比较之前,先把他们的长度一致
3、然后再依次比较

虽说代码量比较大,但整体还是比较清楚的,这个方法稍微是有点“笨”了

# 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 headA == None or headB == None:
            return None
        lA = 0
        lB = 0
        p = headA
        q = headB
        # get length of A
        while p != None:
            lA += 1
            p = p.next
        # get length of B
        while q != None:
            lB += 1
            q = q.next
        
        p = headA
        q = headB
        
        if lA > lB:
            diff = lA - lB
            while diff > 0:
                p = p.next
                diff -= 1
        if lA < lB:
            diff = lB - lA
            while diff > 0:
                q = q.next
                diff -= 1
        while p != None and q!= None:
            if p.val == q.val:
                return p
            p = p.next
            q = q.next
        return None

你可能感兴趣的:(第四十二天 Intersection of Two Linked Lists)