题解 | #两个链表的第一个公共结点#

两个链表的第一个公共结点

https://www.nowcoder.com/practice/6ab1d9a29e88450685099d45c9e31e46

# -*- coding:utf-8 -*-
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None
class Solution:
    def FindFirstCommonNode(self, pHead1, pHead2):
        a,b,c = 0,0,0
        head1 = pHead1
        head2 = pHead2

        def length(node):
            if not node:
                return 0
            return 1 + length(node.next)
        # 求出pHead1和Phead2的链表长度
        a = length(head1)
        b = length(head2)
        # 求差值,然后将它们移到并行的位置
        c = a - b
        while c > 0:
            head1 = head1.next
            c = c - 1
        while c < 0:
            head2 = head2.next
            c = c + 1
        # 同时开始移动,直到找到第一个公共结点
        while head1 != head2:
            head1 = head1.next
            head2 = head2.next
        return head1

#我的实习求职记录#
全部评论

相关推荐

07-23 12:04
门头沟学院 Java
现在是很缺人吗
码农索隆:缺分母,不缺分子,这样好作为炫耀的资本
点赞 评论 收藏
分享
码砖:求职岗位要突出,一眼就能看到,教育背景放到最后,学校经历没那么重要,项目要重点突出
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务