牛客-剑指offer系列题解:两个链表的第一个公共结点

记录刷题的过程。牛客和力扣中都有相关题目,这里以牛客的题目描述为主。该系列默认采用python语言。

1、问题描述:
输入两个链表,找出它们的第一个公共结点。(注意因为传入数据是链表,所以错误测试数据的提示是用其他方式显示的,保证传入数据是正确的)

2、数据结构:
链表

3、题解:
双指针法:先找出一个链表1比链表2多出的K值,然后让链表1多走K,再循环比较大小

# -*- 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
        def equalpoint(firstpoint,secondpoint,pHead1,pHead2):#注意函数参数的正确使用
            #找出链表长度之间的差值
            k = 0
            while secondpoint:
                secondpoint = secondpoint.next
                k += 1
            #先让长的那个走K步
            firstpoint = pHead1
            secondpoint = pHead2
            for i in range(k):
                secondpoint = secondpoint.next
            while firstpoint != secondpoint:
                firstpoint = firstpoint.next
                secondpoint = secondpoint.next
            return firstpoint
        firstpoint = pHead1
        secondpoint = pHead2
        while firstpoint and secondpoint:
            if firstpoint == secondpoint:
                return firstpoint
            firstpoint = firstpoint.next
            secondpoint = secondpoint.next        
        if secondpoint:
            equalpoint(firstpoint,secondpoint,pHead1,pHead2)
        if firstpoint:
            equalpoint(secondpoint,firstpoint,pHead2,pHead1)

简化版:

class Solution:
    def FindFirstCommonNode(self, pHead1, pHead2):
        node1, node2 = pHead1, pHead2

        while node1 != node2:
            node1 = node1.next if node1 else pHead2
            node2 = node2.next if node2 else pHead1

        return node1

4、复杂度分析:
时间复杂度:O(N)
空间复杂度:O(1)

你可能感兴趣的:(牛客-剑指offer系列题解)