用户注册



邮箱:

密码:

用户登录


邮箱:

密码:
记住登录一个月忘记密码?

发表随想


还能输入:200字
云代码 - python代码库

python相交链表

2024-04-24 作者: Python自学举报

[python]代码库

class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next

def getIntersectionNode(headA, headB):
    if headA is None or headB is None:
        return None

    currA = headA
    currB = headB

    while currA != currB:
        currA = headB if currA is None else currA.next
        currB = headA if currB is None else currB.next

    return currA

# Example usage
# Create the first linked list: 1 -> 2 -> 3 -> 4 -> 5
headA = ListNode(1)
headA.next = ListNode(2)
headA.next.next = ListNode(3)
headA.next.next.next = ListNode(4)
headA.next.next.next.next = ListNode(5)

# Create the second linked list: 6 -> 7 -> 8 -> 4 -> 5
headB = ListNode(6)
headB.next = ListNode(7)
headB.next.next = ListNode(8)
headB.next.next.next = headA.next.next.next  # Intersection point
headB.next.next.next.next = headA.next.next.next.next

# Find the intersection point
intersection = getIntersectionNode(headA, headB)

if intersection:
    print("Intersection point value:", intersection.val)
else:
    print("No intersection point found.")


网友评论    (发表评论)


发表评论:

评论须知:

  • 1、评论每次加2分,每天上限为30;
  • 2、请文明用语,共同创建干净的技术交流环境;
  • 3、若被发现提交非法信息,评论将会被删除,并且给予扣分处理,严重者给予封号处理;
  • 4、请勿发布广告信息或其他无关评论,否则将会删除评论并扣分,严重者给予封号处理。


扫码下载

加载中,请稍后...

输入口令后可复制整站源码

加载中,请稍后...