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

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

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

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

相关推荐

评论
1
收藏
分享

创作者周榜

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