You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

LeetCode160 相交链表解法对应的可运行驱动代码如何实现

相交链表驱动代码实现

你需要先实现单链表节点类,再构造符合要求的相交测试用例,再调用你的解法进行验证,完整可运行代码如下:

# 定义单链表节点类
class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next

# 你的解法代码
class Solution:
    def getIntersectionNode(self, headA, headB):
        Alst = {}
        while headA is not None:
            Alst[headA] = headA
            headA = headA.next
        while headB is not None:
            if headB in Alst:
                return headB
            headB = headB.next
        return None

# 构造相交链表的工具函数
def build_intersect_lists(a_unique, b_unique, common):
    # 先构造公共部分
    common_head = None
    cur = None
    for val in common:
        if not common_head:
            common_head = ListNode(val)
            cur = common_head
        else:
            cur.next = ListNode(val)
            cur = cur.next
    # 构造A的独立部分
    headA = None
    cur_a = None
    for val in a_unique:
        if not headA:
            headA = ListNode(val)
            cur_a = headA
        else:
            cur_a.next = ListNode(val)
            cur_a = cur_a.next
    # 把A的尾部接公共部分
    if cur_a:
        cur_a.next = common_head
    else:
        headA = common_head
    # 构造B的独立部分
    headB = None
    cur_b = None
    for val in b_unique:
        if not headB:
            headB = ListNode(val)
            cur_b = headB
        else:
            cur_b.next = ListNode(val)
            cur_b = cur_b.next
    # 把B的尾部接公共部分
    if cur_b:
        cur_b.next = common_head
    else:
        headB = common_head
    return headA, headB, common_head

if __name__ == "__main__":
    # 示例测试用例:A独立部分[4,1],B独立部分[5,6,1],公共部分[8,4,5],相交节点为值是8的节点
    headA, headB, expected = build_intersect_lists([4,1], [5,6,1], [8,4,5])
    sol = Solution()
    res = sol.getIntersectionNode(headA, headB)
    if res:
        print(f"相交节点的值为:{res.val}")
        print(f"是否和预期一致:{res == expected}")
    else:
        print("两个链表无相交节点")

运行上述代码后输出为:

相交节点的值为:8
是否和预期一致:True

如果需要测试无相交的场景,把公共部分参数传空列表即可,此时会输出无相交节点。整个运行过程不会修改原有链表结构,符合题目要求。

内容的提问来源于stack exchange,提问作者RaphC

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 13:45:11