LeetCode刷题记录——第160题(相交链表)

题目描述

编写一个程序,找到两个单链表相交的起始节点。

如下面的两个链表:
LeetCode刷题记录——第160题(相交链表)_第1张图片
在节点 c1 开始相交。

示例 1:
LeetCode刷题记录——第160题(相交链表)_第2张图片

输入:intersectVal = 2, listA = [0,9,1,2,4], listB = [3,2,4], skipA = 3, skipB = 1
输出:Reference of the node with value = 2
输入解释:相交节点的值为 2 (注意,如果两个列表相交则不能为 0)。从各自的表头开始算起,链表 A 为 [0,9,1,2,4],链表 B 为 [3,2,4]。在 A 中,相交节点前有 3 个节点;在 B 中,相交节点前有 1 个节点。

示例2
LeetCode刷题记录——第160题(相交链表)_第3张图片

输入:intersectVal = 0, listA = [2,6,4], listB = [1,5], skipA = 3, skipB = 2
输出:null
输入解释:从各自的表头开始算起,链表 A 为 [2,6,4],链表 B 为 [1,5]。由于这两个链表不相交,所以 intersectVal 必须为 0,而 skipA 和 skipB 可以是任意值。
解释:这两个链表不相交,因此返回 null。

思路分析

  • 方法一:利用数组存储链表中的元素,然后逆序查找
  • 方法二:先求两个链表的长度,然后在让相对长的链表走到跟短链表相同长度的位置,然后再一起遍历,找到相等(位置,地址都相等,这里是个坑)的位置,返回。若没有找到,返回None。

思路链接:https://leetcode-cn.com/problems/two-sum/solution/python3zhi-jie-fa-by-pandawakaka/

代码示例

# 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):
        if headA == None or headB == None:
            return None
        p = []
        q = []
        while headA:
            p.append(headA)
            headA = headA.next
        while headB:
            q.append(headB)
            headB = headB.next
        count = -1
        target = None
        l1 = len(p)
        l2 = len(q)
        while -count<=l1 and -count<=l2:
            if q[count] == p[count]:
                target = p[count]
                count -= 1
            else:
                break
        return target
# 方法二
class Solution(object):
    def getIntersectionNode(self, headA, headB):
        """
        :type head1, head1: ListNode
        :rtype: ListNode
        """
        if headA==None or headB==None:
            return None
        p = headA
        count1 = 0
        while p:
            count1 += 1
            p = p.next
            
        q = headB
        count2 = 0
        while q:
            count2 += 1
            q = q.next
            
        while count1>count2:
            headA = headA.next
            count1 -= 1
            
        while count1<count2:
            headB = headB.next
            count2 -= 1
        
        while headA:
            if headA==headB:
                return headA
            else:
                headA, headB = headA.next,headB.next
        return None
  • 2019年6月28日 于北大图书馆

你可能感兴趣的:(菜鸟的LeetCode刷题记录)