面试题52:两个链表的第一个公共结点

题目描述:

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

解题思路:

链表1长m;链表2长n
思路一:两层for循环 时间复杂度O(mn)
思路二:引入两个辅助栈
思路三:先遍历一遍得到长度差,在遍历比较
#0.首先遍历一遍两个链表,得到他们的长度m,n
#1.然后计算长度差为d,另长表先走d步,然后短表也开始遍历。
#2.当遍历到第一个相同地址时,即为第一个公共节点。
#3.时间复杂度为O(m+n)

思路三
# -*- coding:utf-8 -*-
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None
class Solution:
    def FindFirstCommonNode(self, pHead1, pHead2):
        # write code here
        p1 = pHead1
        p2 = pHead2
        len1 = 0
        len2 = 0
        #首先遍历一遍得到链表的长度
        while p1:
            len1 += 1
            p1 = p1.next
        while p2:
            len2 += 1
            p2 = p2.next
        diff = len1-len2
        plong = pHead1
        pshort = pHead2
        if diff < 0:
            plong = pHead2
            pshort = pHead1
            diff = abs(diff)
        #先让长链表走几步
        for i in range(diff):
            plong = plong.next
        #两个链表一起走
        while plong and pshort:
            if plong.val == pshort.val:
                return plong
            plong = plong.next
            pshort = pshort.next
        return None

你可能感兴趣的:(面试题52:两个链表的第一个公共结点)