【牛客剑指offer刷题】:Python:36.两个链表的第一个公共结点

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

时间限制:1秒 空间限制:32768K 热度指数:192897
本题知识点: 链表
算法知识视频讲解

题目描述

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

法1.

两条相交的链表呈Y型。可以从两条链表尾部同时出发,最后一个相同的结点就是链表的第一个相同的结点。可以利用栈来实现。时间复杂度有O(m + n), 空间复杂度为O(m + n)

代码

链接:https://www.nowcoder.com/questionTerminal/6ab1d9a29e88450685099d45c9e31e46
来源:牛客网

# -*- coding:utf-8 -*-
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None
class Solution:
    def FindFirstCommonNode(self, pHead1, pHead2):
        if not pHead1 or not pHead2:
            return None
         
        stack1 = []
        stack2 = []
         
        while pHead1:
            stack1.append(pHead1)
            pHead1 = pHead1.next
             
        while pHead2:
            stack2.append(pHead2)
            pHead2 = pHead2.next
             
        first = None
        while stack1 and stack2:
            top1 = stack1.pop()
            top2 = stack2.pop()
            if top1 is top2:
                first = top1
            else:
                break
        return first

法2.

思路一其实利用栈主要解决就是同时到达第一个结点的问题。那么从链表头出发如何同时到达第一个相同的结点呢? 链表的长度相同就可以,其实就是走的结点数目相同。所以可以让其中长的链表先走几步,剩余的长度到短链表的长度相同。

# -*- 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
        if not pHead1 or not pHead2:
            return None
        
        p1, p2 = pHead1, pHead2
        length1 = length2 = 0
        while p1:
            length1 += 1
            p1 = p1.next 
        while p2:
            length2 += 1
            p2 = p2.next

        if length1 > length2:
            while length1 - length2:
                pHead1 = pHead1.next
                length1 -= 1
        else:
            while length2 - length1:
                pHead2 = pHead2.next
                length2 -= 1
        while pHead1 and pHead2:
            if pHead1 is pHead2:
                return pHead1
            pHead1 = pHead1.next
            pHead2 = pHead2.next
        return None

链接:https://www.nowcoder.com/questionTerminal/6ab1d9a29e88450685099d45c9e31e46
来源:牛客网

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值