剑指offer 37 两个链表的第一个公共结点

来源:互联网 发布:mastercam数控车编程 编辑:程序博客网 时间:2024/06/05 23:42

题目描述

输入两个链表,找出它们的第一个公共结点。

思路

先统计出两个链表的长度,然后遍历长的链表,得到一个位置,使得长度和短的链表相同。最后同时遍历长的链表和短的链表,找到相同的结点。

代码

class Solution:    def FindFirstCommonNode(self, pHead1, pHead2):        # write code here        len1 = 0        len2 = 0        p1 = pHead1        p2 = pHead2        while p1 != None:            len1 += 1        while p2 != None:            len2 += 1        if len1 > len2:            count = len1 - len2            while count != 0:                p1 = p1.next                count -= 1        elif len2 > len1:            count = len2 -len1            while count != 0:                p2 = p2.next                count -= 1        while p1 != p2:            p1 = p1.next            p2 = p2.next        return p1
原创粉丝点击