Leetcode练习(Python):链表类:第160题:相交链表:编写一个程序,找到两个单链表相交的起始节点。

题目:

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

如下面的两个链表:

在节点 c1 开始相交。

思路:

看了一下想到了使用哈希表,这个很方便,肯定还有其他的方法,之后再补充。

程序:

# 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:
        reservoir = set()
        myNode1 = headA
        myNode2 = headB
        while myNode1:
            reservoir.add(myNode1)
            myNode1 = myNode1.next
        while myNode2:
            if myNode2 in reservoir:
                return myNode2
            myNode2 = myNode2.next
        return None
原文地址:https://www.cnblogs.com/zhuozige/p/12813447.html